﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Collections;
using System.ComponentModel;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Xml;
using System.IO;
using System.Text;
using System.Transactions;
using WebServiceSmart.Router;
using Thrift.Transport;
using Thrift.Protocol;
using Thrift.Route;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using log4net;
using System.Security.Cryptography;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading;
using WebServiceSmart.Model;
using MySql.Data.MySqlClient;
using System.Drawing;
using WebServiceShopping.Thrift;
using System.Linq.Expressions;
using WebServiceShopping.Model;
using System.Collections.ObjectModel;

namespace WebServiceSmart
{
    public partial class MyService
    {
        private const string BIAOSHOPFILE = "s_files";
#if DEBUG
        private const string _addOrderUrl = ""; //debug下不能直接调用接口
#else
        private const string _addOrderUrl = "http://yunli.q5688.com:8090/api/Order";
#endif
        private const string BIAOCH = "s_shopchuanhua";
        private const string BIAOUSERCOMPANY = "s_usercompany";
        private const string BIAOCOMPANYREPAIR = "s_usercompanyrepairlist";



        private const string _churl = "https://openapi.tf56.com/service/api";

        private const string SQLCOMPANYREPAIR = "repair_createtime,repair_repairid,repair_orderprice," +
            "repair_userid,repair_username,repair_userphone,repair_companyid,repair_companyname,repair_companystar," +
            "repair_shopid,repair_shopstar,repair_companydefalut,repair_shopdefalut";


        #region 传化开户 作废

        [WebMethod(Description = "传化分账开户 作废")]
        [Obsolete]
        public string Shop_CH_openaccount(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");

            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
            try
            {
                Dictionary<string, object> paramMap = new Dictionary<string, object>();
                //公共参数
                //paramMap.Add("appid", "1000293");
                paramMap.Add("appid", "3657278");//聚合盛
                //paramMap.Add("appid", "3656932");//通通发
                paramMap.Add("tf_timestamp", DateTime.Now.ToString("yyyyMMddHHmmss"));
                //paramMap.Add("service_id", "tf56pay.mWallet.index2");
                paramMap.Add("service_id", "tf56pay.mWallet.index");
                paramMap.Add("sign_type", "RSA");
                paramMap.Add("version", "v1.0.0");
                //paramMap.Add("trm_type", "02");
                paramMap.Add("trm_type", comrcv.Map_Args["trm_type"]);
                var userIp = string.Empty;
                try
                {
                    userIp = Context.Request.ServerVariables.Get("Remote_Addr").ToString();
                }
                catch { }
                paramMap.Add("client_ip", userIp);

                //paramMap.Add("ext_user_id", "15023692925"); //用户验证ID
                paramMap.Add("ext_user_id", comrcv.Map_Args["c_id"]); //用户验证ID
                paramMap.Add("mobile", comrcv.Map_Args["phone"]); //用户电话号码 必须
                paramMap.Add("user_type", "01");//会员类型 必须  01 个人 02 企业  
                //paramMap.Add("create_type", "1"); //开户类型 必须 1微商户 2商户钱包用户
                //paramMap.Add("merchant_type", "02"); //商户注册类型，会员类型企业必传。个人只能传04 必须 01法人 02其他组织 03个体工商户 04自然人
                paramMap.Add("notify_url", "http://www.juhesell.com:11091/Shop/ChuanHuaBack"); //回调地址
                //paramMap.Add("tf_sign", ZhiFuSignature.GetSignature("D:\\chuanhuafpx\\2013001-rafile3ceshi.pfx", "741963", paramMap));
                paramMap.Add("tf_sign", ZhiFuSignature.GetSignature("D:\\chuanhuafpx\\RSAJUHESHENG.pfx", "juhesheng01", paramMap));
                //paramMap.Add("tf_sign", ZhiFuSignature.GetSignature("D:\\chuanhuafpx\\RSAzhengshugzttfwl.pfx", "ly198999", paramMap));
                loginfo.Info(paramMap);
                var url = PostWebResponseUri(_churl, paramMap);
                loginfo.Info(url);

                ret.Map_Args.Add("Url", url);
                ret.Byte_Flag = 1;
            }
            catch (Exception ex)
            {
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 临时文件转永久文件，内部方法，带附件的表更新数据时都必须调用此方法

        /// <summary>
        /// 临时文件转永久文件
        /// </summary>
        /// <param name="fileIds">附件id，多个用逗号隔开</param>
        /// <returns></returns>
        private void ConvertTemporary(mysqlcli mainsql, string fileIds)
        {
            if (string.IsNullOrWhiteSpace(fileIds)) return;
            var ids = fileIds.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
            if (ids.Length == 0) return;
            using (var ds = mainsql.SqlExcuteWithReturn(string.Format("select * from {0} where file_istemporary=0 and file_id in ('{1}')", BIAOSHOPFILE, string.Join("','", ids))))
            {
                try
                {
                    string basePath = Server.MapPath("~/ShoppingFile");
                    string PathStr = "//fixed//" + DateTime.Now.ToString("yyyy//MM//dd") + "//";
                    string dir = Path.GetDirectoryName(basePath + PathStr);
                    if (!Directory.Exists(dir))
                        Directory.CreateDirectory(dir);
                    foreach (DataRow item in ds.Rows)
                    {
                        var id = item["file_id"].ToString();
                        var paras = new List<MySqlParameter>();
                        paras.Add(new MySqlParameter("@id", id));
                        var path = Server.MapPath("~/" + item["file_path"].ToString());
                        if (File.Exists(path))
                        {
                            paras.Add(new MySqlParameter("@FilePath", "ShoppingFile" + PathStr + Path.GetFileName(path)));
                            File.Copy(path, basePath + PathStr + Path.GetFileName(path), true);
                        }
                        else
                        {
                            return;
                        }
                        path = Server.MapPath("~/" + item["file_small_path"].ToString());
                        if (File.Exists(path))
                        {
                            paras.Add(new MySqlParameter("@smallPath", "ShoppingFile" + PathStr + Path.GetFileName(path)));
                            File.Copy(path, basePath + PathStr + Path.GetFileName(path), true);
                        }
                        else
                        {
                            return;
                        }
                        mainsql.SqlExcuteNoReturn(string.Format("Update {0} set file_istemporary=0,file_path=@FilePath,file_small_path=@smallPath where file_id=@id", BIAOSHOPFILE), paras.ToArray());
                    }
                }
                catch (Exception e)
                {
                    ILog logJieKou = LogManager.GetLogger("LoggerJieKou");
                    logJieKou.Info("临时文件转换：" + e);
                }
            }
        }
        #endregion

        #region 删除附件
        /// <summary>
        /// 删除附件
        /// </summary>
        /// <param name="fileIds">附件id，多个用逗号隔开</param>
        /// <returns></returns>
        private void Shop_DelFile(mysqlcli mainsql, string fileIds)
        {
            if (string.IsNullOrWhiteSpace(fileIds)) return;
            var ids = fileIds.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
            if (ids.Length == 0) return;
            mainsql.SqlExcuteNoReturn(string.Format("Update {0} set file_deleteflag=1 where file_id in ('{1}')", BIAOSHOPFILE, string.Join("','", ids)));
        }
        #endregion

        #region 附件上传
        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg">
        /// FileName 附件文件名
        /// BuffLength 文件大小（字节数）
        /// BuffByte 文件内容
        /// FileType 文件类型：1图片
        /// userid 当前用户
        /// </param>
        /// <returns></returns>
        [WebMethod(Description = "小程序上传附件数据-----上传加密，返回加密，图片生成缩略图")]
        public string Shop_UploadFile(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerJieKou");
            logJieKou.Info("上传附件");

            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                int flag = comrcv.Byte_Flag;
                if (flag == 1)//上传临时附件
                {
                    using (TransactionScope tsall = new TransactionScope())
                    {
                        string FileName = comrcv.Map_Args["FileName"];
                        string id = Guid.NewGuid().ToString();
                        string BuffLengthstr = comrcv.Map_Args["BuffLength"];
                        int BuffLength = 0;
                        int.TryParse(BuffLengthstr, out BuffLength);
                        byte[] valuebyte = Convert.FromBase64String(comrcv.Map_Args["BuffByte"]);

                        string path = "ShoppingFile//temporary//" + DateTime.Now.ToString("yyyy//MM//dd") + "//";
                        string PathStr = Server.MapPath("~/" + path);
                        logJieKou.Info(PathStr);
                        string dir = Path.GetDirectoryName(PathStr);
                        if (!Directory.Exists(dir))
                            Directory.CreateDirectory(dir);
                        string ShortPathStr = Guid.NewGuid() + ".jpg";
                        var filePath = path + id + Path.GetExtension(FileName);
                        PathStr = PathStr + id + Path.GetExtension(FileName);
                        if (File.Exists(PathStr))
                        {
                            FileStream fs = new FileStream(PathStr, FileMode.Truncate);//重新定义
                            fs.Write(valuebyte, 0, BuffLength);
                            fs.Close();
                        }
                        else
                        {
                            FileStream fs = new FileStream(PathStr, FileMode.OpenOrCreate);//重新定义
                            fs.Write(valuebyte, 0, BuffLength);
                            fs.Close();
                        }
                        List<MySqlParameter> paras = new List<MySqlParameter>();
                        paras.Add(new MySqlParameter("@id", id));
                        paras.Add(new MySqlParameter("@FilePath", filePath));
                        paras.Add(new MySqlParameter("@OrgFileName", FileName));
                        paras.Add(new MySqlParameter("@FileSize", BuffLength));
                        paras.Add(new MySqlParameter("@userid", comrcv.Map_Args["userid"]));
                        var fileType = comrcv.Map_Args["FileType"].ToInt32();
                        if (comrcv.Map_Args["FileType"] == "1") //图片附件
                        {
                            fileType = 1;
                            //压缩图片代码，速度过慢已注释，后期有需要用其他方式
                            //int width = 200, height = 150;
                            //if (comrcv.Map_Args.ContainsKey("width"))
                            //    width = (comrcv.Map_Args["width"]).ToInt32();
                            //if (comrcv.Map_Args.ContainsKey("height"))
                            //    height = (comrcv.Map_Args["height"]).ToInt32();
                            //if (MakeThumbnail(valuebyte, Server.MapPath("~/" + path + ShortPathStr), width, height))
                            paras.Add(new MySqlParameter("@smallPath", path + ShortPathStr));
                        }
                        else
                        {
                            paras.Add(new MySqlParameter("@smallPath", DbType.String) { Value = DBNull.Value });
                        }
                        paras.Add(new MySqlParameter("@FileType", fileType));

                        mainsql.SqlExcuteNoReturn(
                            string.Format("insert into {0}(file_id,file_create_time,file_create_user,file_deleteflag,file_type,file_path,file_small_path,file_org_name,file_size,file_istemporary)values"
                            + "(@id,NOW(),@userid,0,@FileType,@FilePath,@smallPath,@OrgFileName,@FileSize,0)", BIAOSHOPFILE), paras.ToArray());

                        ret.Map_Args.Add("Path", filePath);
                        ret.Map_Args.Add("FileId", id);

                        mainsql.closesql();
                        tsall.Complete();
                    }
                }
                else
                {
                    goto EXIT;
                }
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                mainsql.closesql();
                logJieKou.Info(ex);
                goto EXIT;
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="img">图片数据</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>    
        private bool MakeThumbnail(byte[] img, string thumbnailPath, int width, int height, string mode = "W")
        {
            using (MemoryStream ms = new System.IO.MemoryStream(img))
            {
                Image originalImage = Image.FromStream(ms);

                int towidth = width;
                int toheight = height;

                int x = 0;
                int y = 0;
                int ow = originalImage.Width;
                int oh = originalImage.Height;

                switch (mode)
                {
                    case "HW"://指定高宽缩放（可能变形）                
                        break;
                    case "W"://指定宽，高按比例                    
                        toheight = originalImage.Height * width / originalImage.Width;
                        break;
                    case "H"://指定高，宽按比例
                        towidth = originalImage.Width * height / originalImage.Height;
                        break;
                    case "Cut"://指定高宽裁减（不变形）                
                        if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                        {
                            oh = originalImage.Height;
                            ow = originalImage.Height * towidth / toheight;
                            y = 0;
                            x = (originalImage.Width - ow) / 2;
                        }
                        else
                        {
                            ow = originalImage.Width;
                            oh = originalImage.Width * height / towidth;
                            x = 0;
                            y = (originalImage.Height - oh) / 2;
                        }
                        break;
                    default:
                        break;
                }

                //新建一个bmp图片
                Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

                //新建一个画板
                Graphics g = System.Drawing.Graphics.FromImage(bitmap);

                //设置高质量插值法
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                //设置高质量,低速度呈现平滑程度
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //清空画布并以透明背景色填充
                g.Clear(Color.Transparent);

                //在指定位置并且按指定大小绘制原图片的指定部分
                g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                    new Rectangle(x, y, ow, oh),
                    GraphicsUnit.Pixel);

                try
                {
                    //以jpg格式保存缩略图
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    return true;
                }
                catch (System.Exception e)
                {
                    ILog logJieKou = LogManager.GetLogger("LoggerJieKou");
                    logJieKou.Info("缩略图：" + e.Message);
                }
                finally
                {
                    originalImage.Dispose();
                    bitmap.Dispose();
                    g.Dispose();
                }
            }
            return false;
        }

        #endregion

        #region 下载附件base64
        [WebMethod(Description = "下载附件base64")]
        [Obsolete("未实现")]
        public string XCX_GetFile(string msg)
        {
            mysqlcli mainsql = new mysqlcli();
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
            ComThriftMsg retInfo = new ComThriftMsg();
            retInfo.Byte_Flag = -1;
            retInfo.Map_Args = new Dictionary<string, string>();
            retInfo.Map_Args.Add("ErrorMsg", "服务器异常");

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif


            try
            {

                //string PathStr = "D://CompanyConfig//" + NetInfo.Companyaccount + "//" + LogoFilename;
                //if (File.Exists(PathStr))
                //{
                //    FileInfo fileInf = new FileInfo(PathStr);
                //    int buffLength = (int)fileInf.Length;
                //    byte[] bytes = new byte[buffLength];
                //    FileStream fs = fileInf.OpenRead();
                //    int contentLen = fs.Read(bytes, 0, buffLength);
                //    retInfo.Map_Args.Add("FileStringA", Convert.ToBase64String(bytes));

                //    fs.Dispose();
                //}
                //else
                //{
                //    retInfo.Map_Args["ErrorMsg"] = "没有相关图片信息";  //参数错误
                //    goto EXIT;
                //}

                retInfo.Byte_Flag = 1;
            }
            catch (Exception ex)
            {
                retInfo.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                mainsql.closesql();
            }
        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(retInfo, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;

        }
        #endregion

        #region 用户登录

        #region 用户登录
        [WebMethod(Description = "用户登录/注册")]
        public string Shop_AppLoginUser(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");

            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var phone = comrcv.Map_Args["phone"];
                    loginfo.Info("用户登录:" + phone);
                    var code = new Random().Next(100000, 999999);
                    var index = SmsSendInterface.sendOnce(phone, $"您的短信验证码是：{code}。我们不会以任何方式向您索取该密码，请勿告知他人。");
                    ret.Map_Args.Add("MsgCode", index.ToString());
                    ret.Map_Args.Add("Code", code.ToString());
                    var model = mainsql.SqlExcuteWithReturn($"select user_onlyid,user_name from {BIAOUSER} where user_phone='{phone}'").ToModels().FirstOrDefault();
                    string userid = string.Empty;
                    string name = string.Empty;
                    if (model == null)
                    {
                        userid = Guid.NewGuid().ToString().ToLower();
                        name = "新用户";
                        mainsql.SqlExcuteNoReturn($"insert into {BIAOUSER}(user_onlyid,user_phone,user_name) values('{userid}','{phone}','{name}')");
                    }
                    else
                    {
                        userid = model["user_onlyid"];
                        name = model["user_name"];
                    }
                    ret.Map_Args.Add("user_onlyid", userid);
                    ret.Map_Args.Add("user_name", name);

                    var list = mainsql.SqlExcuteWithReturn(string.Format("select t1.shop_id,t2.shop_name,t2.shop_account from {0} t1 left join {2} t2 on t1.shop_id=t2.shop_id where user_id='{1}' and t1.shop_user_deleteflag=0", BIAOSHOPUSER, userid, BIAOSHOP)).ToModels();

                    ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
                    ret.Maplist_MapArgs.Add("Datas", list);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion




        #endregion

        #region 店铺

        private const string BIAOUSER = "yonghualluser";
        private const string BIAOSHOP = "s_shop";
        private const string BIAOSHOPEDIT = "s_shopedit";
        private const string BIAOSHOPUSER = "s_shopuser";
        private const string BIAOSHOPCAR = "s_shopcar";
        private const string BIAOSHOPTAGS = "s_tags";
        private const string BIAOSHOPCONFIG = "s_config";
        private const string SQLALLSHOP = "shop_id,shop_name,shop_tel_number2,shop_title_id,shop_logo_ids,shop_short_descript,shop_level,shop_reputation,shop_create_time,shop_create_user,shop_deleteflag,shop_tel_number,shop_tel_name,shop_address,shop_order_number,shop_good_number,shop_see_number,shop_comp_number,shop_status,shop_longitude,shop_latitude";

        #region 验证用户是否关联店铺
        [WebMethod(Description = "验证用户是否关联店铺，返回店铺ID")]
        public string Shop_VerShopUser(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");


            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userid"];
                    loginfo.Info("验证用户是否关联店铺:" + userId);
                    var list = mainsql.SqlExcuteWithReturn(string.Format("select t1.shop_id,t2.shop_name,t2.shop_account from {0} t1 left join {2} t2 on t1.shop_id=t2.shop_id where user_id='{1}' and t1.shop_user_deleteflag=0", BIAOSHOPUSER, userId, BIAOSHOP)).ToModels();

                    ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
                    ret.Maplist_MapArgs.Add("Datas", list);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 申请店铺

        [WebMethod(Description = "申请店铺")]
        public string Shop_ShopAdd(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_ShopAdd) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif
            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userid"];
                    var account = comrcv.Map_Args["Account"];
                    //if ((mainsql.SqlExecuteScalar(string.Format("select count(1) from {0} where UserId='{1}' and DeleteFlag=0", BIAOSHOPUSER, userId)).ToInt32()) > 0)
                    //{
                    //    ret.Map_Args["ErrorMsg"] = "已有店铺，不能重复申请";  //当前用户已有店铺
                    //    mainsql.closesql();
                    //    goto EXIT;
                    //}
                    if ((mainsql.SqlExecuteScalar(string.Format("select count(1) from {0} where shop_account='{1}' and shop_deleteflag=0", BIAOSHOP, account)).ToInt32()) > 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "账号已存在";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    int RandKey = 0;
                RandKey:
                    Thread.Sleep(1);
                    Random ran = new Random();
                    int key = ran.Next(1000, 9999);
                    if (key == RandKey)
                    {
                        goto RandKey;
                    }
                    if (mainsql.SqlExecuteScalar($"select count(1) from {BIAOSHOP} where shop_tuiguangma='{key}'").ToInt32() > 0)
                    {
                        goto RandKey;
                    }

                    var y1 = comrcv.Map_Args["YYZZ1"];
                    var y2 = comrcv.Map_Args["YYZZ2"];
                    var photo = comrcv.Map_Args["Photo"];
                    var fileIds = string.Format("{0},{1},{2}", y1, y2, photo);
                    ConvertTemporary(mainsql, fileIds);

                    StringBuilder sqlStr = new StringBuilder();
                    sqlStr.AppendFormat("insert into {0}({1},shop_descript,shop_account,shop_password,shop_business1,shop_business2,shop_doorwayphoto,shop_tuiguangma) values"
                        + "(@id,@name,@title,'',@file,@sdescript,0,0,NOW(),@userid,0,@telphone,@telname,@address,0,0,0,0,2,@point1,@point2,null,@account,@password,@y1,@y2,@photo,@tuiguangma)"
                        , BIAOSHOP, SQLALLSHOP);
                    var shopId = Guid.NewGuid().ToString();
                    List<MySqlParameter> paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@id", shopId));
                    paras.Add(new MySqlParameter("@tuiguangma", key));
                    paras.Add(new MySqlParameter("@name", comrcv.Map_Args["Name"]));
                    paras.Add(new MySqlParameter("@title", string.Empty));
                    paras.Add(new MySqlParameter("@file", string.Empty));
                    paras.Add(new MySqlParameter("@account", account));
                    paras.Add(new MySqlParameter("@password", comrcv.Map_Args["Password"]));
                    paras.Add(new MySqlParameter("@userid", userId));
                    paras.Add(new MySqlParameter("@y1", y1));
                    paras.Add(new MySqlParameter("@y2", y2));
                    paras.Add(new MySqlParameter("@photo", photo));
                    //paras.Add(new MySqlParameter("@sdescript", comrcv.Map_Args["ShortDescript"]));
                    //paras.Add(new MySqlParameter("@telphone", comrcv.Map_Args["TelNumber"]));
                    //paras.Add(new MySqlParameter("@telname", comrcv.Map_Args["TelName"]));
                    //paras.Add(new MySqlParameter("@address", comrcv.Map_Args["Address"]));
                    //paras.Add(new MySqlParameter("@point1", comrcv.Map_Args["PointY"]));
                    //paras.Add(new MySqlParameter("@point2", comrcv.Map_Args["PointX"]));
                    paras.Add(new MySqlParameter("@sdescript", string.Empty));
                    paras.Add(new MySqlParameter("@telphone", string.Empty));
                    paras.Add(new MySqlParameter("@telname", string.Empty));
                    paras.Add(new MySqlParameter("@address", string.Empty));
                    paras.Add(new MySqlParameter("@point1", string.Empty));
                    paras.Add(new MySqlParameter("@point2", string.Empty));

                    if (mainsql.SqlExcuteNoReturn(sqlStr.ToString(), paras.ToArray()) != 1)
                    {
                        ret.Map_Args["ErrorMsg"] = "系统繁忙";  //插入数据内部错误
                        mainsql.closesql();
                        goto EXIT;
                    }

                    mainsql.SqlExcuteNoReturn($"insert into {BIAOSHOPUSER}(user_id,shop_id,shop_user_index,shop_user_create_time,shop_user_create_user,shop_user_deleteflag)"
                        + $"values('{userId}','{shopId}',1,NOW(),'{userId}',0)");

                    //车辆品牌
                    var carIds = comrcv.Map_Args["carIds"];
                    var ids1 = carIds?.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                    var paraShop = new MySqlParameter("@ShopId", shopId);
                    var paraUser = new MySqlParameter("@userid", userId);
                    foreach (var item in ids1)
                    {
                        mainsql.SqlExcuteNoReturn(string.Format("Insert into {0}(shop_id,car_type_id,shop_car_create_time,shop_car_create_user,shop_car_deleteflag)values"
                            + "(@ShopId,@CarTypeId,NOW(),@userid,0)", BIAOSHOPCAR), paraShop, paraUser, new MySqlParameter("@CarTypeId", item));
                    }
                    ret.Map_Args.Add("ShopId", shopId);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 店铺登录绑定
        [WebMethod(Description = "店铺登录绑定")]
        public string Shop_Login(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_Login) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userid"];
                    var account = comrcv.Map_Args["Account"];
                    var pass = comrcv.Map_Args["Password"];
                    bool isFirst = true;
                First:
                    var ds = mainsql.SqlExcuteWithReturn(string.Format("select shop_id,shop_name,shop_balance,shop_status from {0} where shop_account='{2}' and shop_password='{3}'", BIAOSHOP, SQLALLSHOP, account, pass));
                    if (ds.Rows.Count == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "账号或密码错误";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    var shopId = ds.Rows[0]["shop_id"].ToString();
                    if (isFirst && !shopId.Equals(mainsql.SqlExecuteScalar(string.Format("select shop_id from {0} where user_id='{1}' and shop_id='{2}' and shop_user_deleteflag=0", BIAOSHOPUSER, userId, shopId))?.ToString()))
                    {
                        var index = (mainsql.SqlExecuteScalar(string.Format("select max(shop_user_index) from {0} where shop_id='{1}'", BIAOSHOPUSER, shopId))).ToInt32();
                        index++;
                        var paras = new List<MySqlParameter>();
                        paras.Add(new MySqlParameter("@userid", userId));
                        paras.Add(new MySqlParameter("@ShopId", shopId));
                        paras.Add(new MySqlParameter("@OrderIndex", index));
                        mainsql.SqlExcuteNoReturn(string.Format("insert into {0}(user_id,shop_id,shop_user_index,shop_user_create_time,shop_user_create_user,shop_user_deleteflag)values"
                            + "(@userid,@ShopId,@OrderIndex,NOW(),@userid,0)", BIAOSHOPUSER), paras.ToArray());
                        isFirst = false;
                        goto First;
                    }
                    ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
                    //已绑定，直接返回店铺信息
                    ret.Maplist_MapArgs.Add("Shop", ds.ToModels());

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 店铺登录
        [WebMethod(Description = "店铺登录")]
        public string Shop_LoginPwd(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_LoginPwd) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userid"];
                    var shopId = comrcv.Map_Args["ShopId"];
                    var pass = comrcv.Map_Args["Password"];

                    var ds = mainsql.SqlExcuteWithReturn(string.Format("select shop_id,shop_name,shop_balance,shop_status from {0} where shop_id='{1}' and shop_password='{2}'", BIAOSHOP, shopId, pass)).ToModels();
                    if (ds.Count == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "密码错误";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    if (mainsql.SqlExecuteScalar(string.Format("select count(1) from {0} where user_id='{1}' and shop_id='{2}' and shop_user_deleteflag=0", BIAOSHOPUSER, userId, shopId)).ToInt32() == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "没有管理权限";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
                    ret.Maplist_MapArgs.Add("Shop", ds);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 店铺密码修改
        [WebMethod(Description = "店铺密码修改")]
        public string Shop_UpdateShopPwd(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_UpdateShopPwd) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userid"];
                    var shopId = comrcv.Map_Args["ShopId"];
                    var pass = comrcv.Map_Args["Password"];
                    var npass = comrcv.Map_Args["NewPassword"];

                    var index = mainsql.SqlExecuteScalar(string.Format("select count(1) from {0} where shop_id='{2}' and shop_password='{3}'", BIAOSHOP, SQLALLSHOP, shopId, pass)).ToInt32();
                    if (index == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "密码错误";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    if (mainsql.SqlExecuteScalar(string.Format("select count(1) from {0} where user_id='{1}' and shop_id='{2}' and shop_user_deleteflag=0", BIAOSHOPUSER, userId, shopId)).ToInt32() == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "没有管理权限";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    mainsql.SqlExcuteNoReturn($"update {BIAOSHOP} set shop_password='{npass}' where shop_id='{shopId}'");

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 根据店铺ID查询店铺信息
        [WebMethod(Description = "根据店铺ID查询店铺信息")]
        public string Shop_FindShopById(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_FindShopById) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var shopId = comrcv.Map_Args["ShopId"];

                    var ds = mainsql.SqlExcuteWithReturn(string.Format("select t1.*,t2.c_id,t2.c_account as c_userid,t2.user_chxinyong from {0} t1 left join {3} t2 on t1.shop_id=t2.shop_id where t1.shop_id='{2}'", BIAOSHOP, SQLALLSHOP, shopId, BIAOCH));
                    if (ds.Rows.Count == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "店铺不存在";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
                    var lis = ds.ToModels();
                    foreach (var item in lis)
                    {
                        if (item.ContainsKey("shop_title_id"))
                        {
                            var fileId = item["shop_title_id"];
                            if (!string.IsNullOrWhiteSpace(fileId))
                            {
                                var ids = fileId.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                                var files = mainsql.SqlExcuteWithReturn($"select file_id,file_path from {BIAOSHOPFILE} where file_id in ('{string.Join("','", ids)}')").ToModels();
                                ret.Maplist_MapArgs.Add("Title", files);
                            }
                        }
                        if (item.ContainsKey("shop_logo_ids"))
                        {
                            var fileId = item["shop_logo_ids"];
                            if (!string.IsNullOrWhiteSpace(fileId))
                            {
                                var ids = fileId.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                                var files = mainsql.SqlExcuteWithReturn($"select file_id,file_path from {BIAOSHOPFILE} where file_id in ('{string.Join("','", ids)}')").ToModels();
                                ret.Maplist_MapArgs.Add("LogoFile", files);
                            }
                        }
                    }
                    ret.Maplist_MapArgs.Add("Shop", lis);

                    //店铺车辆品牌信息
                    ret.Maplist_MapArgs.Add("Cars", mainsql.SqlExcuteWithReturn(string.Format("select car_type_id from {0} where shop_car_deleteflag=0 and shop_id='{1}' order by shop_car_create_time", BIAOSHOPCAR, shopId)).ToModels());

                    var openmsg = mainsql.SqlExecuteScalar($"select c_name from {BIAOSHOPCONFIG} where c_type='openshop'")?.ToString();
                    ret.Map_Args.Add("openshopmsg", openmsg);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 根据店铺ID查询店铺首页信息
        [WebMethod(Description = "根据店铺ID查询店铺首页信息")]
        public string Shop_FindShopInfoById(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_AppLoginUser) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var shopId = comrcv.Map_Args["ShopId"];

                    var ds = mainsql.SqlExcuteWithReturn(string.Format("select t1.*,t2.user_chxinyong from {0} t1 left join {3} t2 on t1.shop_id=t2.shop_id where t1.shop_id='{2}'", BIAOSHOP, SQLALLSHOP, shopId, BIAOCH));
                    if (ds.Rows.Count == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "店铺不存在";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
                    //店铺基础信息  
                    var lis = ds.ToModels();
                    foreach (var item in lis)
                    {
                        if (item.ContainsKey("shop_title_id"))
                        {
                            var fileId = item["shop_title_id"];
                            if (!string.IsNullOrWhiteSpace(fileId))
                            {
                                var ids = fileId.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                                var files = mainsql.SqlExcuteWithReturn($"select file_id,file_path from {BIAOSHOPFILE} where file_id in ('{string.Join("','", ids)}')").ToModels();
                                ret.Maplist_MapArgs.Add("Title", files);
                            }
                        }
                        if (item.ContainsKey("shop_logo_ids"))
                        {
                            var fileId = item["shop_logo_ids"];
                            if (!string.IsNullOrWhiteSpace(fileId))
                            {
                                var ids = fileId.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                                var files = mainsql.SqlExcuteWithReturn($"select file_id,file_path from {BIAOSHOPFILE} where file_id in ('{string.Join("','", ids)}')").ToModels();
                                ret.Maplist_MapArgs.Add("LogoFile", files);
                            }
                        }
                    }
                    ret.Maplist_MapArgs.Add("Shop", lis);
                    //店铺车辆品牌信息
                    ret.Maplist_MapArgs.Add("Cars", mainsql.SqlExcuteWithReturn(string.Format("select car_type_id from {0} where shop_car_deleteflag=0 and shop_id='{1}' order by shop_car_create_time", BIAOSHOPCAR, shopId)).ToModels());
                    //店铺标签
                    ret.Maplist_MapArgs.Add("Tags", mainsql.SqlExcuteWithReturn(string.Format("select tag_name,COUNT(tag_name) as count from {0} where shop_id='{1}' and tag_deleteflag=0 GROUP BY tag_name ORDER BY COUNT(tag_name)", BIAOSHOPTAGS, shopId)).ToModels());

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 店铺信息编辑
        [WebMethod(Description = "店铺信息编辑")]
        public string Shop_EditShop(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_EditShop) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userid"];
                    var shopId = comrcv.Map_Args["ShopId"];
                    var shop = mainsql.SqlExcuteWithReturn(string.Format("select shop_id,shop_logo_ids,shop_title_id,shop_status from {0} where shop_id='{1}' and shop_deleteflag=0", BIAOSHOP, shopId)).ToModels().FirstOrDefault();
                    if (shop == null)
                    {
                        ret.Map_Args["ErrorMsg"] = "不存在的店铺";  //当前用户已有店铺
                        mainsql.closesql();
                        goto EXIT;
                    }
                    //var status = shop["shop_status"].ToInt32();
                    //if (status != 0 && status != 2)
                    //{
                    //    ret.Map_Args["ErrorMsg"] = "店铺异常，不允许编辑";
                    //    mainsql.closesql();
                    //    goto EXIT;
                    //}
                    //logo附件
                    var fileIds = comrcv.Map_Args["files"];
                    ConvertTemporary(mainsql, fileIds);
                    var titleId = comrcv.Map_Args["title"];
                    ConvertTemporary(mainsql, titleId);
                    //被删除的附件
                    var ids1 = fileIds?.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                    var ids2 = shop["shop_logo_ids"]?.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
                    foreach (var item in ids1)
                    {
                        if (ids2.Contains(item)) ids2.Remove(item);
                    }
                    var title = shop["shop_title_id"]?.ToString();
                    if (!string.IsNullOrWhiteSpace(title) && title != titleId)
                        ids2.Add(title);

                    if (ids2.Count > 0)
                        Shop_DelFile(mainsql, string.Join(",", ids2));

                    //车辆品牌
                    var carIds = comrcv.Map_Args["carIds"];
                    ids1 = carIds?.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                    StringBuilder sqlStr = new StringBuilder();
                    sqlStr.AppendFormat("insert into {0}(shop_name,shop_title_id,shop_logo_ids,shop_short_descript,shop_descript,shop_account,shop_create_time,shop_create_user,"
                        + "shop_tel_number,shop_tel_name,shop_address,shop_longitude,shop_latitude,shop_cars,shop_id,shop_isedit) values", BIAOSHOPEDIT);
                    sqlStr.AppendFormat("(@Name,@title,@file,@ShortDescript,@Descript,@account,NOW(),@userid,@TelNumber,@TelName,@Address,@point1,@point2,@shop_cars,@id,0)");

                    List<MySqlParameter> paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@userid", userId));
                    paras.Add(new MySqlParameter("@id", shopId));
                    paras.Add(new MySqlParameter("@Name", comrcv.Map_Args["Name"]));
                    paras.Add(new MySqlParameter("@file", fileIds));
                    paras.Add(new MySqlParameter("@title", titleId));
                    paras.Add(new MySqlParameter("@ShortDescript", comrcv.Map_Args["ShortDescript"]));
                    paras.Add(new MySqlParameter("@Descript", comrcv.Map_Args["Descript"]));
                    paras.Add(new MySqlParameter("@account", comrcv.Map_Args["Account"]));
                    paras.Add(new MySqlParameter("@TelNumber", comrcv.Map_Args["TelNumber"]));
                    paras.Add(new MySqlParameter("@TelNumber2", comrcv.Map_Args.ContainsKey("TelNumber2") ? comrcv.Map_Args["TelNumber2"] : string.Empty));
                    paras.Add(new MySqlParameter("@TelName", comrcv.Map_Args["TelName"]));
                    paras.Add(new MySqlParameter("@Address", comrcv.Map_Args["Address"]));
                    paras.Add(new MySqlParameter("@point1", comrcv.Map_Args["PointY"]));
                    paras.Add(new MySqlParameter("@point2", comrcv.Map_Args["PointX"]));
                    paras.Add(new MySqlParameter("@shop_cars", string.Join(",", ids1)));

                    mainsql.SqlExcuteNoReturn(sqlStr.ToString(), paras.ToArray());

                    mainsql.SqlExcuteNoReturn($"update {BIAOSHOP} set shop_title_id=@title,shop_logo_ids=@file,shop_short_descript=@ShortDescript,shop_account=@account"
                        + ",shop_tel_number=@TelNumber,shop_tel_number2=@TelNumber2,shop_tel_name=@TelName,shop_address=@Address,shop_longitude=@point1,shop_latitude=@point2 where shop_id=@id", paras.ToArray());

                    //mainsql.SqlExcuteNoReturn(string.Format("delete from {0} where shop_id='{1}'", BIAOSHOPCAR, shopId));
                    //var paraShop = new MySqlParameter("@ShopId", shopId);
                    //var paraUser = new MySqlParameter("@userid", userId);
                    //foreach (var item in ids1)
                    //{
                    //    mainsql.SqlExcuteNoReturn(string.Format("Insert into {0}(shop_id,car_type_id,shop_car_create_time,shop_car_create_user,shop_car_deleteflag)values"
                    //        + "(@ShopId,@CarTypeId,NOW(),@userid,0)", BIAOSHOPCAR), paraShop, paraUser, new MySqlParameter("@CarTypeId", item));
                    //}

                    ret.Map_Args.Add("ShopId", shopId);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 关闭店铺
        [WebMethod(Description = "关闭店铺")]
        public string Shop_CloseShop(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_CloseShop) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userid"];
                    var shopId = comrcv.Map_Args["ShopId"];
                    var status = comrcv.Map_Args["Status"].ToInt32();
                    if (status != 0 && status != 2)
                    {
                        ret.Map_Args["ErrorMsg"] = "参数错误";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    var shop = mainsql.SqlExecuteScalar(string.Format("select shop_status from {0} where shop_id='{1}' and shop_deleteflag=0", BIAOSHOP, shopId))?.ToString();
                    if (string.IsNullOrWhiteSpace(shop))
                    {
                        ret.Map_Args["ErrorMsg"] = "不存在的店铺";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    if (!"0".Equals(shop) && !"2".Equals(shop))
                    {
                        ret.Map_Args["ErrorMsg"] = "当前店铺异常，请联系客服";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    if (mainsql.SqlExecuteScalar(string.Format("select count(1) from {0} where user_id='{1}' and shop_id='{2}' and shop_user_deleteflag=0", BIAOSHOPUSER, userId, shopId)).ToInt32() == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "没有管理权限";
                        mainsql.closesql();
                        goto EXIT;
                    }

                    StringBuilder sqlStr = new StringBuilder();
                    sqlStr.AppendFormat("Update {0} set shop_status={1} where shop_id=@id"
                        , BIAOSHOP, status);
                    List<MySqlParameter> paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@id", shopId));

                    mainsql.SqlExcuteNoReturn(sqlStr.ToString(), paras.ToArray());


                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 店铺添加标签
        [WebMethod(Description = "店铺添加标签")]
        public string Shop_ShopAddTag(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_ShopAddTag) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userid"];
                    var shopId = comrcv.Map_Args["ShopId"];
                    var tagName = comrcv.Map_Args["Tag"];
                    var shop = mainsql.SqlExecuteScalar(string.Format("select shop_id from {0} where shop_id='{1}' and shop_deleteflag=0", BIAOSHOP, shopId))?.ToString();
                    if (string.IsNullOrWhiteSpace(shop))
                    {
                        ret.Map_Args["ErrorMsg"] = "不存在的店铺";  //当前用户已有店铺
                        mainsql.closesql();
                        goto EXIT;
                    }
                    if (mainsql.SqlExecuteScalar(string.Format("select count(1) from {0} where shop_id='{1}' and tag_name='{2}' and tag_create_user='{3}'", BIAOSHOPTAGS, shopId, tagName, userId)).ToInt32() == 0)
                    {
                        mainsql.SqlExcuteNoReturn(string.Format("insert into {0}(shop_id,tag_name,tag_create_time,tag_create_user,tag_deleteflag)values"
                            + "(@ShopId,@Name,NOW(),@userid,0)", BIAOSHOPTAGS), new MySqlParameter("@ShopId", shopId), new MySqlParameter("@Name", tagName), new MySqlParameter("@userid", userId));
                    }
                    else
                    {
                        ret.Map_Args["ErrorMsg"] = "不能重复添加";
                        mainsql.closesql();
                        goto EXIT;
                    }

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 查询经营范围的列表
        [WebMethod(Description = "查询经营范围的列表")]
        public string Shop_GetAllShopType(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetAllShopType) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
                    ret.Maplist_MapArgs.Add("Datas", mainsql.SqlExcuteWithReturn($"select c_id as car_id,c_name as car_name,c_first_pingyin as car_first_pingyin,c_parent_id as car_parent_id,c_logo as car_logo,c_index as car_index from {BIAOSHOPCONFIG} where c_type='cartype' order by c_index").ToModels());

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 查询店铺人员列表
        [WebMethod(Description = "查询店铺人员列表")]
        public string Shop_GetAllShopUser(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetAllShopUser) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var shopId = comrcv.Map_Args["ShopId"];
                    ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
                    ret.Maplist_MapArgs.Add("Datas", mainsql.SqlExcuteWithReturn($"select t1.*,t2.user_phone,t2.user_name,t2.user_openid_juhesheng from {BIAOSHOPUSER} t1 left join {BIAOUSER} t2 on t1.user_id=t2.user_onlyid where shop_id='{shopId}' and t1.shop_user_deleteflag='0' order by shop_user_index").ToModels());

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 店铺人员移除
        [WebMethod(Description = "店铺人员移除")]
        public string Shop_DelShopUser(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_DelShopUser) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"];
                    var delId = comrcv.Map_Args["deluserid"];
                    var shopId = comrcv.Map_Args["ShopId"];
                    mainsql.SqlExcuteNoReturn($"Update {BIAOSHOPUSER} set shop_user_deleteflag=1,shop_user_create_time=NOW(),shop_user_create_user='{userid}' where user_id='{delId}' and shop_id='{shopId}'");

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 输入用户手机号，添加店铺人员
        [WebMethod(Description = "输入用户手机号，添加店铺人员")]
        public string Shop_AddShopUser(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_AddShopUser) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"];
                    var adduser = comrcv.Map_Args["user_phone"];
                    var shopId = comrcv.Map_Args["ShopId"];
                    var model = mainsql.SqlExcuteWithReturn($"select user_onlyid,user_name from {BIAOUSER} where user_phone='{adduser}'").ToModels().FirstOrDefault();
                    if (model == null)
                    {
                        ret.Map_Args["ErrorMsg"] = "用户不存在";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    var addid = model["user_onlyid"];
                    if (mainsql.SqlExecuteScalar($"select count(1) from {BIAOSHOPUSER} where shop_id='{shopId}' and user_id='{addid}'").ToInt32() > 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "用户已存在";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    var index = mainsql.SqlExecuteScalar($"select max(shop_user_index) from {BIAOSHOPUSER} where shop_id='{shopId}'").ToInt32();
                    index++;
                    mainsql.SqlExcuteNoReturn($"insert into {BIAOSHOPUSER}(user_id,shop_id,shop_user_index,shop_user_create_time,shop_user_create_user,shop_user_deleteflag)"
                        + $"values('{addid}','{shopId}',{index},NOW(),'{userid}',0)");
                    ret.Map_Args.Add("user_id", addid);
                    ret.Map_Args.Add("user_name", model["user_name"]);
                    ret.Map_Args.Add("user_phone", adduser);

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 店铺的收藏人员列表
        [WebMethod(Description = "店铺的收藏人员列表")]
        public string Shop_GetAllCollUser(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetAllCollUser) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var shopId = comrcv.Map_Args["ShopId"];
                    var lis = mainsql.SqlExcuteWithReturn($"select user_id,shop_coll_create_time,user_name,user_phone from {BIAOBUYERCOLLSHOP} t1 left join {BIAOUSER} t2 on t1.user_id=t2.user_onlyid where shop_id='{shopId}' and shop_coll_deleteflag=0 order by shop_coll_create_time desc").ToModels();

                    ret.Maplist_MapArgs.Add("Datas", lis);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 增加店铺浏览次数
        [WebMethod(Description = "增加店铺浏览次数")]
        public string Shop_addShopSee(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_addShopSee) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    //var userId = comrcv.Map_Args["userid"];
                    var shopId = comrcv.Map_Args["ShopId"];

                    var number = mainsql.SqlExecuteScalar($"update {BIAOSHOP} set shop_see_number=shop_see_number+1 where shop_id='{shopId}';"
                        + $"select shop_see_number from {BIAOSHOP} where shop_id='{shopId}'").ToInt32();
                    ret.Map_Args.Add("shop_see_number", number.ToString());

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 开关消息通知
        [WebMethod(Description = "开关消息通知")]
        public string Shop_ShopEditMsg(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_ShopEditMsg) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userid"];
                    var shopId = comrcv.Map_Args["ShopId"];
                    var isOpen = comrcv.Map_Args["IsOpen"].ToInt32();//0关1开

                    var number = mainsql.SqlExecuteScalar($"update {BIAOSHOPUSER} set shop_user_ismsg={isOpen} where shop_id='{shopId}' and user_id='{userId}'");

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 查询货款宝商家信息
        [WebMethod(Description = "查询货款宝商家信息")]
        public string Shop_ShopFindXinYong(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_ShopFindXinYong) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var shopId = comrcv.Map_Args["ShopId"];

                    var models = mainsql.SqlExcuteWithReturn($"select * from {BIAOCH} where shop_id='{shopId}'").ToModels().FirstOrDefault();
                    if (models != null)
                        foreach (var item in models)
                        {
                            if (!ret.Map_Args.ContainsKey(item.Key))
                                ret.Map_Args.Add(item.Key, item.Value);
                        }
                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 修改货款宝商家信息
        [WebMethod(Description = "修改货款宝商家信息")]
        public string Shop_ShopUpdateXinYong(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_ShopUpdateXinYong) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userid"];
                    var shopId = comrcv.Map_Args["ShopId"];
                    var phone = comrcv.Map_Args["Phone"];

                    var index = mainsql.SqlExcuteNoReturn($"update {BIAOCH} set c_code='{phone}' where shop_id='{shopId}'");
                    if (index == 0)
                    {
                        index = mainsql.SqlExcuteNoReturn($"insert into {BIAOCH} (shop_id,c_create_time,c_create_user,c_deleteflag,c_code,user_chxinyong)"
                              + $"values('{shopId}',NOW(),'{userId}',0,'{phone}',0)");
                        if (index == 0)
                        {
                            ret.Map_Args["ErrorMsg"] = "插入数据失败，请联系管理员。";
                            mainsql.closesql();
                            goto EXIT;
                        }
                    }
                    else if (index != 1)
                    {
                        ret.Map_Args["ErrorMsg"] = "数据异常，请联系管理员。";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #endregion

        #region 产品

        private const string BIAOPRODUCT = "s_product";
        private const string BIAOPPARAMS = "s_productparameter";
        private const string BIAOPSPECS = "s_productspecs";
        private const string BIAOPSPVALUE = "s_productspecvalue";
        private const string BIAOPSKU = "s_productSKU";
        private const string BIAOPSKUVALUE = "s_productSKUValues";
        private const string BIAOPRODUCTYPE = "s_producttype";
        private const string BIAOHUODONG = "s_huodong";
        private const string BIAOHUODONGPRD = "s_huodongprd";
        private const string BIAOHUODONGSHOP = "s_huodongshop";


        #region 分页查询产品（列表管理）
        [WebMethod(Description = "分页查询产品（列表管理）")]
        public string Shop_GetProductPage(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetProductPage) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userid"];
                    var shopId = comrcv.Map_Args["ShopId"];
                    var pageIndex = comrcv.Map_Args["pageIndex"].ToInt32();
                    pageIndex = pageIndex == 0 ? 1 : pageIndex;
                    var pageSize = comrcv.Map_Args["pageSize"].ToInt32();
                    pageSize = pageSize == 0 ? 10 : pageSize;

                    var shop = mainsql.SqlExecuteScalar(string.Format("select shop_id from {0} where shop_id='{1}' and shop_deleteflag=0", BIAOSHOP, shopId))?.ToString();
                    if (string.IsNullOrWhiteSpace(shopId))
                    {
                        ret.Map_Args["ErrorMsg"] = "不存在的店铺";
                        mainsql.closesql();
                        goto EXIT;
                    }

                    StringBuilder sql = new StringBuilder();
                    sql.AppendFormat("select * from (select t1.*,t2.file_small_path from {0} t1 left join {1} t2 on t1.prd_cover_id=t2.file_id) as tb where prd_deleteflag=0 and shop_id='{2}'", BIAOPRODUCT, BIAOSHOPFILE, shopId);
                    var paras = new List<MySqlParameter>();
                    //paras.Add(new MySqlParameter("@ShopId", shopId));
                    if (comrcv.Map_Args.ContainsKey("name"))
                    {
                        var val = comrcv.Map_Args["name"];
                        if (!string.IsNullOrWhiteSpace(val))
                        {
                            sql.Append(" and prd_name=@Name");
                            paras.Add(new MySqlParameter("@Name", val));
                        }
                    }
                    if (comrcv.Map_Args.ContainsKey("Status"))
                    {
                        var val = comrcv.Map_Args["Status"].ToInt32();
                        if (val == 0 || val == 1)
                        {
                            sql.Append(" and prd_status=@Status");
                            paras.Add(new MySqlParameter("@Status", val));
                        }
                    }
                    sql.AppendFormat(" order by prd_index desc limit {0},{1}", pageIndex * pageSize - pageSize, pageSize);

                    var lis = mainsql.SqlExcuteWithReturn(sql.ToString(), paras.ToArray()).ToModels();
                    foreach (var item in lis)
                    {
                        item.Remove("prd_deleteflag");
                    }
                    ret.Maplist_MapArgs.Add("Datas", lis);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 买家查询产品列表，带条件搜索
        [WebMethod(Description = "买家查询产品列表，带条件搜索")]
        public string Shop_GetProductList(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetProductList) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var pageIndex = comrcv.Map_Args["pageIndex"].ToInt32();
                    pageIndex = pageIndex == 0 ? 1 : pageIndex;
                    var pageSize = comrcv.Map_Args["pageSize"].ToInt32();
                    pageSize = pageSize == 0 ? 10 : pageSize;

                    var sumModel = mainsql.SqlExcuteWithReturn("select sum(prd_see_number)/count(1) as SeeNumber,sum(prd_sale_number)/count(1) as SaleNumber from " + BIAOPRODUCT).ToModels().FirstOrDefault();
                    double n1 = 0, n2 = 0, maxLevel = 5;

                    if (sumModel != null)
                    {
                        n1 = sumModel["SeeNumber"].ToDouble();//浏览
                        n2 = sumModel["SaleNumber"].ToDouble();//销售
                    }
                    StringBuilder sql = new StringBuilder();
                    //销量40 浏览量10 店铺等级40 优惠价格10
                    sql.AppendFormat("select * from (select ((case when t1.prd_sale_number>={3} then 40 else t1.prd_sale_number/{3}*40 end)+(case when t1.prd_see_number>={2} then 10 else t1.prd_see_number/{2}*10 end)+(t3.shop_level/{5}*40)+((t1.prd_price-t1.prd_dis_price)/t1.prd_price*10))as rownumber"
                        + ",t1.prd_id,t1.prd_name,t1.prd_short_descript,t1.prd_type_id,t1.prd_price,t1.prd_dis_price,t1.prd_sale_number,t1.prd_freight,t2.file_small_path "
                        + "from {0} t1 left join {1} t2 on t1.prd_cover_id=t2.file_id left join {4} t3 on t1.shop_id=t3.shop_id where t1.prd_status=1 and t1.prd_deleteflag=0) as tb where 1=1 ", BIAOPRODUCT, BIAOSHOPFILE, n1, n2, BIAOSHOP, maxLevel);
                    var paras = new List<MySqlParameter>();
                    //产品类型
                    if (comrcv.Map_Args.ContainsKey("typeid"))
                    {
                        var val = comrcv.Map_Args["typeid"];
                        if (!string.IsNullOrWhiteSpace(val))
                        {
                            sql.Append(" and prd_type_id like @TypeId");
                            paras.Add(new MySqlParameter("@TypeId", val + "%"));
                        }
                    }
                    //产品名
                    if (comrcv.Map_Args.ContainsKey("name"))
                    {
                        var val = comrcv.Map_Args["name"];
                        if (!string.IsNullOrWhiteSpace(val))
                        {
                            sql.Append($" and prd_name like @Name");
                            paras.Add(new MySqlParameter("@Name", "%" + val.Trim('%') + "%"));
                        }
                    }
                    sql.AppendFormat(" order by rownumber desc limit {0},{1}", pageIndex * pageSize - pageSize, pageSize);

                    var lis = mainsql.SqlExcuteWithReturn(sql.ToString(), paras.ToArray()).ToModels();
                    ret.Maplist_MapArgs.Add("Datas", lis);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 买家查询店铺列表，带条件搜索
        [WebMethod(Description = "买家查询店铺列表，带条件搜索")]
        public string Shop_GetShopList(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetShopList) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var pageIndex = comrcv.Map_Args["pageIndex"].ToInt32();
                    pageIndex = pageIndex == 0 ? 1 : pageIndex;
                    var pageSize = comrcv.Map_Args["pageSize"].ToInt32();
                    pageSize = pageSize == 0 ? 10 : pageSize;

                    StringBuilder sql = new StringBuilder();
                    sql.AppendFormat("select t1.shop_id,t1.shop_name,t1.shop_short_descript,t1.shop_level,t1.shop_tel_number,t1.shop_tel_number2,t1.shop_tel_name,t1.shop_address,t1.shop_order_number,t1.shop_good_number,t1.shop_ation,t2.file_small_path as Title,t3.user_chxinyong from {0} t1 left join {1} t2 on t1.shop_title_id=t2.file_id left join {2} t3 on t1.shop_id=t3.shop_id where t1.shop_deleteflag=0 and t1.shop_status=0", BIAOSHOP, BIAOSHOPFILE, BIAOCH);
                    var paras = new List<MySqlParameter>();
                    //经营范围
                    if (comrcv.Map_Args.ContainsKey("carid"))
                    {
                        var val = comrcv.Map_Args["carid"];
                        if (!string.IsNullOrWhiteSpace(val))
                        {
                            var ids = val.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                            sql = new StringBuilder();
                            sql.AppendFormat("select t4.user_chxinyong,t1.shop_id,t1.shop_name,t1.shop_short_descript,t1.shop_level,t1.shop_tel_number,t1.shop_tel_number2,t1.shop_tel_name,t1.shop_address,t1.shop_order_number,t1.shop_good_number,t1.shop_ation,t2.file_small_path as Title from {0} t1 left join {1} t2 on t1.shop_title_id=t2.file_id inner join (select shop_id from {2} where car_type_id in('" + string.Join("','", ids) + "') group by shop_id) t3 on t1.shop_id=t3.shop_id left join {3} t4 on t1.shop_id=t4.shop_id where t1.shop_deleteflag=0 and t1.shop_status=0", BIAOSHOP, BIAOSHOPFILE, BIAOSHOPCAR, BIAOCH);
                        }
                    }
                    //店铺名
                    //店铺简介
                    if (comrcv.Map_Args.ContainsKey("name"))
                    {
                        var val = comrcv.Map_Args["name"];
                        if (!string.IsNullOrWhiteSpace(val))
                        {
                            sql.Append($" and (shop_name like @name");
                            sql.Append($" or shop_short_descript like @name)");
                            paras.Add(new MySqlParameter("@name", "%" + val.Trim('%') + "%"));
                        }
                    }
                    sql.AppendFormat(" order by shop_ation desc,shop_good_number/shop_order_number DESC,shop_order_number desc,shop_level desc limit {0},{1}", pageIndex * pageSize - pageSize, pageSize);

                    var lis = mainsql.SqlExcuteWithReturn(sql.ToString(), paras.ToArray()).ToModels();
                    ret.Maplist_MapArgs.Add("Datas", lis);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 为热门推荐商品
        [WebMethod(Description = "热门推荐")]
        public string Shop_GetRMShopList(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetShopList) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var pageIndex = comrcv.Map_Args["pageIndex"].ToInt32();
                    pageIndex = pageIndex == 0 ? 1 : pageIndex;
                    var pageSize = comrcv.Map_Args["pageSize"].ToInt32();
                    pageSize = pageSize == 0 ? 3 : pageSize;

                    StringBuilder sql = new StringBuilder();
                    sql.AppendFormat("select t4.h_name,t1.shop_id,t1.shop_name,t1.shop_short_descript,t1.shop_level,t1.shop_tel_number,t1.shop_tel_number2,t1.shop_tel_name,t1.shop_address,t1.shop_order_number,t1.shop_good_number,t1.shop_ation,t2.file_small_path as Title,t3.user_chxinyong from {3} t4 left join {0} t1 on t4.shop_id=t1.shop_id left join {1} t2 on t1.shop_title_id=t2.file_id left join {2} t3 on t1.shop_id=t3.shop_id where t1.shop_deleteflag=0 and t1.shop_status=0 and t4.h_starttime<=NOW() and (t4.h_endtime is null or t4.h_endtime>=NOW())", BIAOSHOP, BIAOSHOPFILE, BIAOCH, BIAOHUODONGSHOP);
                    var paras = new List<MySqlParameter>();

                    sql.AppendFormat(" order by h_index limit {0},{1}", pageIndex * pageSize - pageSize, pageSize);

                    var lis = mainsql.SqlExcuteWithReturn(sql.ToString(), paras.ToArray()).ToModels();
                    ret.Maplist_MapArgs.Add("Datas", lis);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 修理厂

        //通过订单id只丢修理厂修理厂
        public string getProductXiulic(string msg)
        {

            return "";
        }
        //查询所有修理厂


        #endregion

        #region 产品详情查询
        [WebMethod(Description = "产品详情查询")]
        public string Shop_FindProductById(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_FindProductById) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userid"];
                    //var shopId = comrcv.Map_Args["ShopId"];
                    var pId = comrcv.Map_Args["ProductId"];

                    var model = mainsql.SqlExcuteWithReturn(string.Format("select * from (select t1.*,t2.c_name as TypeName,t3.shop_name as ShopName,t4.file_small_path as ShopTitle from {0} as t1 left join {1} as t2 on t1.prd_type_id=t2.c_id left join {3} t3 on t1.shop_id=t3.shop_id left join {4} t4 on t3.shop_title_id=t4.file_id) as t where prd_deleteflag=0 and prd_id='{2}'"
                        , BIAOPRODUCT, BIAOPRODUCTYPE, pId, BIAOSHOP, BIAOSHOPFILE)).ToModels();
                    if (model.Count == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "不存在的产品";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
                    ret.Maplist_MapArgs.Add("Product", model);
                    var fileId = model.FirstOrDefault()["prd_logo_ids"];
                    if (!string.IsNullOrWhiteSpace(fileId))
                    {
                        var ids = fileId.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                        var files = mainsql.SqlExcuteWithReturn($"select file_id,file_path from {BIAOSHOPFILE} where file_id in ('{string.Join("','", ids)}')").ToModels();
                        ret.Maplist_MapArgs.Add("LogoFile", files);
                    }
                    var typeId = model.FirstOrDefault()["prd_type_id"];
                    //参数
                    var productParas = mainsql.SqlExcuteWithReturn(string.Format("select prd_para_name,prd_para_value,prd_para_index from {0} where prd_id='{1}' and prd_para_deleteflag=0", BIAOPPARAMS, pId)).ToModels();
                    ret.Maplist_MapArgs.Add("Params", productParas);
                    //规格
                    var specs = mainsql.SqlExcuteWithReturn(string.Format("select * from {0} where prd_type_id='{1}'", BIAOPSPECS, typeId)).ToModels();
                    ret.Maplist_MapArgs.Add("Specs", specs);
                    //规格值
                    var specVals = mainsql.SqlExcuteWithReturn(string.Format("select * from {0} where prd_id='{1}'", BIAOPSPVALUE, pId)).ToModels();
                    ret.Maplist_MapArgs.Add("SpecVals", specVals);
                    //sku、价格
                    var prices = mainsql.SqlExcuteWithReturn(string.Format("select * from {0} where prd_id='{1}'", BIAOPSKU, pId)).ToModels();
                    var links = mainsql.SqlExcuteWithReturn($"select t.prd_sku_id,t.prd_sps_value from (select t1.* from {BIAOPSKUVALUE} t1 left join {BIAOPSPVALUE} t2 on t1.prd_sps_val_id=t2.prd_sps_val_id where t1.prd_id={pId}) as t").ToModels();
                    foreach (var item in prices)
                    {
                        var valIds = links.Where(x => x["prd_sku_id"] == item["prd_sku_id"]).Select(x => x["prd_sps_value"]);
                        item.Add("SpecVals", string.Join(",", valIds));//价格相关的规格值，需要前端根据用户选择的规格值来查找相应的价格
                    }
                    ret.Maplist_MapArgs.Add("Skus", prices);
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 产品新增/编辑

        [WebMethod(Description = "产品新增/编辑")]
        public string Shop_ModifyProduct(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_ModifyProduct) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userid"];
                    var shopId = comrcv.Map_Args["ShopId"];

                    var shop = mainsql.SqlExecuteScalar(string.Format("select shop_id from {0} where shop_id='{1}' and shop_deleteflag=0", BIAOSHOP, shopId))?.ToString();
                    if (string.IsNullOrWhiteSpace(shop))
                    {
                        ret.Map_Args["ErrorMsg"] = "不存在的店铺";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    if (mainsql.SqlExecuteScalar(string.Format("select count(1) from {0} where user_id='{1}' and shop_id='{2}' and shop_user_deleteflag=0", BIAOSHOPUSER, userId, shopId)).ToInt32() == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "没有管理权限";
                        mainsql.closesql();
                        goto EXIT;
                    }

                    //logo附件
                    var fileIds = comrcv.Map_Args["files"];
                    ConvertTemporary(mainsql, fileIds);

                    //取第一张图片为封面图片
                    var coverfile = string.Empty;
                    if (!string.IsNullOrWhiteSpace(fileIds))
                        coverfile = fileIds.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries)?.FirstOrDefault();

                    var paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@ShopId", shopId));
                    paras.Add(new MySqlParameter("@TypeId", comrcv.Map_Args["TypeId"]));
                    paras.Add(new MySqlParameter("@Name", comrcv.Map_Args["Name"]));
                    paras.Add(new MySqlParameter("@ShortDescript", comrcv.Map_Args["ShortDescript"]));
                    paras.Add(new MySqlParameter("@Descript", comrcv.Map_Args["Descript"]));
                    paras.Add(new MySqlParameter("@CoverFile", coverfile));
                    paras.Add(new MySqlParameter("@logoFile", fileIds));
                    paras.Add(new MySqlParameter("@Price", comrcv.Map_Args["Price"].ToDouble()));
                    paras.Add(new MySqlParameter("@DisPrice", comrcv.Map_Args["DisPrice"].ToDouble()));
                    paras.Add(new MySqlParameter("@userid", userId));
                    paras.Add(new MySqlParameter("@Unit", comrcv.Map_Args["Unit"]));
                    paras.Add(new MySqlParameter("@prd_daifu", comrcv.Map_Args["DaiFu"].ToInt32()));
                    paras.Add(new MySqlParameter("@Freight", comrcv.Map_Args["Freight"].ToDouble()));
                    paras.Add(new MySqlParameter("@FreightNumber", comrcv.Map_Args["FreightNumber"].ToInt32()));
                    paras.Add(new MySqlParameter("@FreightAdd", comrcv.Map_Args["FreightAdd"].ToDouble()));
                    paras.Add(new MySqlParameter("@StockNumber", comrcv.Map_Args["StockNumber"].ToInt32())); //库存，需要统计sku

                    long pId = 0;
                    if (comrcv.Map_Args.ContainsKey("ProductId")) pId = comrcv.Map_Args["ProductId"].ToLong();
                    if (pId == 0)
                    {
                        //新增
                        var index = mainsql.SqlExecuteScalar(string.Format("select max(prd_index) from {0} where shop_id='{1}'", BIAOPRODUCT, shopId)).ToInt32();
                        index++;
                        paras.Add(new MySqlParameter("@OrderIndex", index)); //排序ID，取历史最大值+1
                        pId = mainsql.SqlExecuteScalar(string.Format("insert into {0}(shop_id,prd_type_id,prd_name,prd_short_descript,prd_descript,prd_daifu,prd_freight,prd_freight_number,prd_freight_add,prd_cover_id,prd_logo_ids,prd_price,prd_dis_price,prd_unit,prd_stock_number,prd_index,prd_create_time,prd_create_user,prd_update_time,prd_update_user,prd_deleteflag,prd_status,prd_see_number,prd_sale_number)values"
                            + "(@ShopId,@TypeId,@Name,@ShortDescript,@Descript,@prd_daifu,@Freight,@FreightNumber,@FreightAdd,@CoverFile,@logoFile,@Price,@DisPrice,@Unit,@StockNumber,@OrderIndex,NOW(),@userid,NOW(),@userid,0,0,0,0);SELECT @@IDENTITY", BIAOPRODUCT), paras.ToArray()).ToLong();
                    }
                    else
                    {
                        var status = mainsql.SqlExecuteScalar($"select prd_status from {BIAOPRODUCT} where prd_id={pId}").ToInt32();
                        if (status == 1)
                        {
                            mainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "上架中的产品不能直接修改";
                            goto EXIT;
                        }
                        mainsql.SqlExcuteNoReturn($"update {BIAOPRODUCT} set prd_type_id=@TypeId,prd_name=@Name,prd_short_descript=@ShortDescript,prd_descript=@Descript,prd_cover_id=@CoverFile"
                            + $",prd_daifu=@prd_daifu,prd_freight=@Freight,prd_freight_number=@FreightNumber,prd_freight_add=@FreightAdd,prd_logo_ids=@logoFile,prd_price=@Price,prd_dis_price=@DisPrice,prd_unit=@Unit,prd_stock_number=@StockNumber,prd_update_time=NOW(),prd_update_user=@userid where prd_id={pId}", paras.ToArray());

                        var model = mainsql.SqlExcuteWithReturn($"select prd_id,prd_logo_ids from {BIAOPRODUCT} where prd_id='{pId}' and prd_deleteflag=0").ToModels().FirstOrDefault();
                        if (model == null)
                        {
                            ret.Map_Args["ErrorMsg"] = "产品不存在或已被删除";
                            mainsql.closesql();
                            goto EXIT;
                        }
                        var ids = model["prd_logo_ids"];
                        //被删除的附件
                        var ids1 = fileIds?.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                        var ids2 = ids?.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
                        foreach (var item in ids1)
                        {
                            if (ids2.Contains(item)) ids2.Remove(item);
                        }
                        if (ids2.Count > 0)
                            Shop_DelFile(mainsql, string.Join(",", ids2));

                        mainsql.SqlExcuteNoReturn(string.Format("delete from {0} where prd_id='{1}'", BIAOPPARAMS, pId));
                        //清理以前的规格值和sku
                        mainsql.SqlExcuteNoReturn($"delete from {BIAOPSKUVALUE} where prd_id='{pId}'");
                        mainsql.SqlExcuteNoReturn($"delete from {BIAOPSKU} where prd_id='{pId}'");
                        mainsql.SqlExcuteNoReturn($"delete from {BIAOPSPVALUE} where prd_id='{pId}'");
                    }

                    #region 添加参数
                    if (comrcv.Map_Args.ContainsKey("Params"))
                    {
                        var productParaIndex = 1;
                        var jsonStr = comrcv.Map_Args["Params"];
                        if (!string.IsNullOrWhiteSpace(jsonStr))
                        {
                            JArray json = JsonConvert.DeserializeObject<JArray>(jsonStr);

                            if (json != null && json.Count > 0)
                            {
                                foreach (var item in json)
                                {
                                    var pparas = new List<MySqlParameter>();
                                    pparas.Add(new MySqlParameter("@ProductId", pId));
                                    pparas.Add(new MySqlParameter("@Name", item.Value<string>("Name")));
                                    pparas.Add(new MySqlParameter("@Value", item.Value<string>("Value")));
                                    pparas.Add(new MySqlParameter("@OrderIndex", productParaIndex));
                                    pparas.Add(new MySqlParameter("@userid", userId));
                                    //add
                                    mainsql.SqlExcuteNoReturn($"insert into {BIAOPPARAMS}(prd_id,prd_para_name,prd_para_value,prd_para_index,prd_para_create_time,prd_para_create_user,prd_para_update_time,prd_para_update_user,prd_para_deleteflag)values"
                                        + "(@ProductId,@Name,@Value,@OrderIndex,NOW(),@userid,NOW(),@userid,0)", pparas.ToArray());
                                    productParaIndex++;
                                }
                            }
                        }
                    }
                    #endregion

                    #region 添加规格值、SKU
                    if (comrcv.Maplist_MapArgs != null && comrcv.Maplist_MapArgs.ContainsKey("SpecVals"))
                    {
                        var specVals = comrcv.Maplist_MapArgs["SpecVals"];
                        if (specVals != null && specVals.Count > 0)
                        {
                            var ids = new Dictionary<string, long>();
                            foreach (var item in specVals)
                            {
                                var sparas = new List<MySqlParameter>();
                                sparas.Add(new MySqlParameter("@SpecId", item["SpecId"].ToLong()));
                                sparas.Add(new MySqlParameter("@ProductId", pId));
                                sparas.Add(new MySqlParameter("@Value", item["Value"]));
                                var id = mainsql.SqlExecuteScalar($"Insert into {BIAOPSPVALUE}(prd_sps_id,prd_id,prd_sps_value)values(@SpecId,@ProductId,@Value);"
                                     + "SELECT @@IDENTITY", sparas.ToArray()).ToLong();

                                if (!ids.ContainsKey(item["Value"]))
                                {
                                    ret.Map_Args["ErrorMsg"] = "参数错误：出现相同的规格值";
                                    mainsql.closesql();
                                    goto EXIT;
                                }
                                ids.Add(item["Value"], id);
                            }
                            if (comrcv.Maplist_MapArgs.ContainsKey("Skus"))
                            {
                                var prices = comrcv.Maplist_MapArgs["Skus"];
                                if (prices != null && prices.Count > 0)
                                {
                                    foreach (var item in prices)
                                    {
                                        var skuParas = new List<MySqlParameter>();
                                        skuParas.Add(new MySqlParameter("@Sku", item["Sku"]));
                                        skuParas.Add(new MySqlParameter("@Unit", item["Unit"]));
                                        skuParas.Add(new MySqlParameter("@StockNumber", item["StockNumber"].ToInt32()));
                                        skuParas.Add(new MySqlParameter("@Price", item["Price"].ToDouble()));
                                        skuParas.Add(new MySqlParameter("@DisPrice", item["DisPrice"].ToDouble()));

                                        //添加sku：sku-黑-8-32
                                        var id = mainsql.SqlExecuteScalar($"insert into {BIAOPSKU}(prd_id,prd_sku,prd_sku_unit,prd_sku_stock_number,prd_sku_price,prd_sku_dis_price)values"
                                              + $"({pId},@Sku,@Unit,@StockNumber,@Price,@DisPrice);SELECT @@IDENTITY").ToLong();

                                        var vals = item["SpecVals"]?.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                                        foreach (var vItem in vals)
                                        {
                                            if (!ids.ContainsKey(vItem))
                                            {
                                                ret.Map_Args["ErrorMsg"] = "参数错误：规格值和sku不一致";
                                                mainsql.closesql();
                                                goto EXIT;
                                            }
                                            //添加sku关联值
                                            mainsql.SqlExcuteNoReturn($"insert into {BIAOPSKUVALUE}(prd_id,prd_sku_id,prd_sps_val_id)values({pId},{id},{ids[vItem]})");
                                        }
                                    }
                                }
                            }
                        }
                    }
                    #endregion

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 获取所有产品类型
        [WebMethod(Description = "获取所有产品类型")]
        public string Shop_GetAllProductType(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetAllProductType) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();

                    var productParas = mainsql.SqlExcuteWithReturn(string.Format("select c_id as prd_type_id,c_name as prd_type_name,c_parent_id as prd_type_parent_id,c_index as prd_type_index from {0} where c_type='producttype'", BIAOPRODUCTYPE)).ToModels();
                    ret.Maplist_MapArgs.Add("Datas", productParas);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 首页产品类型配置
        [WebMethod(Description = "获取所有产品类型")]
        public string Shop_GetHomeProductType(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetHomeProductType) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();

                    var ids = mainsql.SqlExecuteScalar($"select c_name from {BIAOSHOPCONFIG} where c_type='hometypes'").ToString();
                    var s = ids.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                    var productParas = mainsql.SqlExcuteWithReturn(string.Format("select c_id as prd_type_id,c_name as prd_type_name,c_parent_id as prd_type_parent_id,c_index as prd_type_index,c_logo from {0} where c_type='producttype' and c_id in('{1}')", BIAOPRODUCTYPE, string.Join("','", s))).ToModels();
                    ret.Maplist_MapArgs.Add("Datas", productParas);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 产品上架/下架
        [WebMethod(Description = "产品上架/下架")]
        [Obsolete]
        public string Shop_UpdateProductStatus(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_UpdateProductStatus) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"];
                    var productId = comrcv.Map_Args["ProductId"].ToLong();
                    var status = comrcv.Map_Args["Status"].ToInt32();

                    var s = mainsql.SqlExecuteScalar($"select prd_status from {BIAOPRODUCT} where prd_id={productId}").ToInt32();
                    if (status == s)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "请勿重复操作";
                        goto EXIT;
                    }
                    else
                    {
                        mainsql.SqlExcuteNoReturn($"update {BIAOPRODUCT} set prd_status={status},prd_update_user='{userid}',prd_update_time=NOW() where prd_id={productId}");
                    }

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 删除产品
        [WebMethod(Description = "删除产品")]
        [Obsolete]
        public string Shop_DelProduct(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_DelProduct) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"];
                    var productId = comrcv.Map_Args["ProductId"].ToLong();

                    var status = mainsql.SqlExecuteScalar($"select prd_status from {BIAOPRODUCT} where prd_id={productId}").ToInt32();
                    if (status == 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "上架中的产品不能直接删除";
                        goto EXIT;
                    }
                    mainsql.SqlExcuteNoReturn($"update {BIAOPRODUCT} set prd_deleteflag=1,prd_update_user='{userid}',prd_update_time=NOW() where prd_id={productId}");

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 修改产品库存
        [WebMethod(Description = "修改产品库存")]
        [Obsolete]
        public string Shop_EditProductStock(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_EditProductStock) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"];
                    var productId = comrcv.Map_Args["ProductId"].ToLong();
                    var number = comrcv.Map_Args["StockNumber"].ToInt32();

                    mainsql.SqlExcuteNoReturn($"update {BIAOPRODUCT} set prd_stock_number={number},prd_update_user='{userid}',prd_update_time=NOW() where prd_id={productId}");

                    #region 添加sku
                    //if (comrcv.Map_Args.ContainsKey("Sku"))
                    //{
                    //    var jsonStr = comrcv.Map_Args["Sku"];
                    //    if (!string.IsNullOrWhiteSpace(jsonStr))
                    //    {
                    //        JArray json = JsonConvert.DeserializeObject<JArray>(jsonStr);

                    //        if (json != null && json.Count > 0)
                    //        {
                    //            foreach (var item in json)
                    //            {
                    //                var sku = item.Value<string>("Sku");
                    //                number = item.Value<int>("StockNumber");
                    //                mainsql.SqlExcuteNoReturn($"update {BIAOPSKU} set StockNumber={number} where ProductId={productId} and Sku='{sku}'");
                    //            }
                    //        }
                    //    }
                    //}
                    #endregion
                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 增加产品浏览次数
        [WebMethod(Description = "增加产品浏览次数")]
        [Obsolete]
        public string Shop_addProductSee(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_addProductSee) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    //var userid = comrcv.Map_Args["userid"];
                    var productId = comrcv.Map_Args["ProductId"].ToLong();

                    var number = mainsql.SqlExecuteScalar($"update {BIAOPRODUCT} set prd_see_number=prd_see_number+1 where prd_id={productId};"
                        + $"select prd_see_number from {BIAOPRODUCT} where prd_id={productId}").ToInt32();

                    ret.Map_Args.Add("prd_see_number", number.ToString());

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 根据活动Id查询活动下的所有产品列表
        [WebMethod(Description = "根据活动Id查询活动下的所有产品列表")]
        public string Shop_GetProductByConfigId(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetProductPage) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var cid = comrcv.Map_Args.ContainsKey("c_id") ? comrcv.Map_Args["c_id"] : "";
                    StringBuilder sql = new StringBuilder();
                    sql.AppendFormat("select * from (select t1.*,t3.h_id as h_configid,t3.h_index as c_index,t2.file_small_path from {2} t3 inner join {0} t1 on t3.prd_id=t1.prd_id left join {1} t2 on t1.prd_cover_id=t2.file_id) as tb",
                        BIAOPRODUCT, BIAOSHOPFILE, BIAOHUODONGPRD, DateTime.Now.ToString("yyyy-MM-dd"));

                    if (string.IsNullOrWhiteSpace(cid))
                    {
                        sql.Append(" where h_configid='1'");
                        sql.Append(" order by c_index,prd_index desc");
                        sql.Append(" limit 0,9");
                    }
                    else
                    {
                        sql.Append(" where h_configid='" + cid + "'");
                        sql.Append(" order by c_index,prd_index desc");
                    }

                    var lis = mainsql.SqlExcuteWithReturn(sql.ToString()).ToModels();
                    ret.Maplist_MapArgs.Add("Datas", lis);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 查询所有活动
        [WebMethod(Description = "查询所有活动")]
        public string Shop_GetProductHuoDong(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetProductPage) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    StringBuilder sql = new StringBuilder();
                    var thisTime = DateTime.Now;
                    sql.AppendFormat("select h_id as c_id,h_index as c_index,h_name as c_name from {0} where h_starttime<='{1}' and (h_endtime is null or h_endtime>='{1}') and h_id<>1 order by h_index", BIAOHUODONG, thisTime.ToString("yyyy-MM-dd HH:mm:ss"));

                    var lis = mainsql.SqlExcuteWithReturn(sql.ToString()).ToModels();
                    ret.Maplist_MapArgs.Add("Datas", lis);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #endregion

        #region 买家
        private const string BIAOBUYERCOLLSHOP = "s_collshop";
        private const string BIAOBUYERCOLLPRODUCT = "s_collproduct";

        #region 收藏的店铺列表
        [WebMethod(Description = "收藏的店铺列表")]
        public string Shop_GetAllCollShop(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetAllCollShop) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "yonghusystem",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userid"];
                    var lis = mainsql.SqlExcuteWithReturn($"select * from (select t1.shop_coll_id as ID,t1.shop_id,t2.shop_name,t1.shop_coll_index as OrderIndex,t3.file_path as Title,t2.shop_short_descript,t2.shop_level,t2.shop_reputation,t2.shop_tel_number,t2.shop_tel_number2,t2.shop_tel_name,t2.shop_address,t2.shop_status from {BIAOBUYERCOLLSHOP} t1 left join {BIAOSHOP} t2 on t1.shop_id=t2.shop_id left join {BIAOSHOPFILE} t3 on t2.shop_title_id=t3.file_id "
                        + $" where t1.user_id='{userId}') as tb order by OrderIndex desc").ToModels();

                    ret.Maplist_MapArgs.Add("Datas", lis);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 验证是否收藏某店铺
        [WebMethod(Description = "验证是否收藏某店铺")]
        public string Shop_VerCollShop(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_VerCollShop) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userid"];
                    var shopId = comrcv.Map_Args["ShopId"];
                    var count = mainsql.SqlExecuteScalar($"select count(1) from {BIAOBUYERCOLLSHOP} where user_id='{userId}' and shop_id='{shopId}'").ToInt32();
                    ret.Map_Args.Add("Count", count.ToString());

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 购物车
        [WebMethod(Description = "购物车")]
        public string Shop_GetAllCollProduct(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetAllCollProduct) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                var userId = comrcv.Map_Args["userid"];
                //以前的产品
                //var lis = mainsql.SqlExcuteWithReturn($"select * from (select t1.prd_coll_id as ID,t2.prd_daifu,t1.prd_id,t1.prd_coll_number,t1.prd_sku,t2.prd_name,t1.prd_coll_index as OrderIndex,t3.file_path as CoverFile,t2.prd_short_descript,t2.prd_status,t2.prd_price,t2.prd_dis_price,t2.prd_unit,t2.prd_stock_number,t2.prd_sale_number,t2.prd_freight,t2.prd_freight_number,t2.prd_freight_add,t2.shop_id,t4.shop_name as ShopName,t5.file_path as ShopTitle from {BIAOBUYERCOLLPRODUCT} t1 left join {BIAOPRODUCT} t2 on t1.prd_id=t2.prd_id left join {BIAOSHOPFILE} t3 on t2.prd_cover_id=t3.file_id left join {BIAOSHOP} t4 on t2.shop_id=t4.shop_id left join {BIAOSHOPFILE} t5 on t4.shop_title_id=t5.file_id "
                //    + $" where t1.user_id='{userId}' and t2.prd_deleteflag=0) as tb order by OrderIndex desc").ToModels();

                //团购商品
                var lis = mainsql.SqlExcuteWithReturn($@"select 
                                a.prd_coll_id,
                                d.file_small_path as filePath,
                                b.commodity_id as productId,b.commodity_name as productName,b.commodity_content as productContent,b.commodity_actual_price as actualPrice,b.commodity_original_price as originalPrice,
                                c.user_id as companyId,c.user_companyname as companyName,
                                a.prd_coll_number as quantity,a.prd_coll_create_time as createTime,a.user_id as createUserId
                                from s_collproduct a
                                inner join s_commodity b on a.prd_id=b.commodity_id and b.commodity_status=1 and b.commodity_isdel=0
                                left  join s_usercompany c on b.company_id=c.user_id
                                left  join s_files d on d.file_id=b.commodity_file_id

                                where a.user_id='{userId}' and a.prd_coll_deleteflag=0 order by a.prd_coll_create_time ").ToModels();


                ret.Maplist_MapArgs.Add("Datas", lis);

                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex.Message);
            }

            mainsql.closesql();
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 收藏/取消收藏店铺
        [WebMethod(Description = "收藏/取消收藏店铺")]
        public string Shop_CollShop(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_CollShop) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"];
                    var shopId = comrcv.Map_Args["ShopId"];

                    var id = mainsql.SqlExecuteScalar($"select shop_coll_id from {BIAOBUYERCOLLSHOP} where user_id='{userid}' and shop_id='{shopId}'").ToLong();
                    if (id > 0)
                    {
                        mainsql.SqlExcuteNoReturn($"DELETE FROM {BIAOBUYERCOLLSHOP} where shop_coll_id='{id}'");
                    }
                    else
                    {
                        var index = mainsql.SqlExecuteScalar($"select max(shop_coll_index) from {BIAOBUYERCOLLSHOP} where user_id='{userid}' and shop_coll_deleteflag=0").ToInt32();
                        index++;
                        var paras = new List<MySqlParameter>();
                        paras.Add(new MySqlParameter("@UserId", userid));
                        paras.Add(new MySqlParameter("@ShopId", shopId));
                        paras.Add(new MySqlParameter("@OrderIndex", index));
                        mainsql.SqlExcuteNoReturn($"insert into {BIAOBUYERCOLLSHOP}(user_id,shop_id,shop_coll_index,shop_coll_create_time,shop_coll_create_user,shop_coll_deleteflag)"
                            + "values(@UserId,@ShopId,@OrderIndex,NOW(),@UserId,0)", paras.ToArray());
                    }

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 收藏产品
        [WebMethod(Description = "收藏产品")]
        public string Shop_CollProduct(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_CollProduct) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"];
                    var productId = comrcv.Map_Args["ProductId"].ToLong();
                    var sku = comrcv.Map_Args.ContainsKey("Sku") ? comrcv.Map_Args["Sku"] : string.Empty;//可空
                    var number = comrcv.Map_Args.ContainsKey("Number") ? comrcv.Map_Args["Number"].ToInt32() : 1; //可空，默认1

                    var id = mainsql.SqlExecuteScalar($"select prd_coll_id from {BIAOBUYERCOLLPRODUCT} where user_id='{userid}' and prd_id='{productId}' "
                        + (string.IsNullOrWhiteSpace(sku) ? string.Empty : " prd_sku='" + sku + "'")).ToLong();
                    if (id > 0)
                    {
                        mainsql.SqlExcuteNoReturn($"UPDATE {BIAOBUYERCOLLPRODUCT} SET prd_coll_number={number} where prd_coll_id='{id}'");
                    }
                    else
                    {
                        var count = mainsql.SqlExecuteScalar($"select count(1) from {BIAOBUYERCOLLPRODUCT} where user_id='{userid}'").ToInt32();
                        if (count >= 50)
                        {
                            ret.Map_Args["ErrorMsg"] = "购物车已满";
                            mainsql.closesql();
                            goto EXIT;
                        }
                        var index = mainsql.SqlExecuteScalar($"select max(prd_coll_index) from {BIAOBUYERCOLLPRODUCT} where user_id='{userid}' and prd_coll_deleteflag=0").ToInt32();
                        index++;
                        var paras = new List<MySqlParameter>();
                        paras.Add(new MySqlParameter("@UserId", userid));
                        paras.Add(new MySqlParameter("@ProductId", productId));
                        paras.Add(new MySqlParameter("@Number", number));
                        paras.Add(new MySqlParameter("@Sku", sku));
                        paras.Add(new MySqlParameter("@OrderIndex", index));
                        mainsql.SqlExcuteNoReturn($"insert into {BIAOBUYERCOLLPRODUCT}(user_id,prd_id,prd_sku,prd_coll_number,prd_coll_index,prd_coll_create_time,prd_coll_create_user,prd_coll_deleteflag)"
                            + "values(@UserId,@ProductId,@Sku,@Number,@OrderIndex,NOW(),@UserId,0)", paras.ToArray());
                    }

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 批量删除收藏的产品
        [WebMethod(Description = "批量删除收藏的产品")]
        public string Shop_DelCollProducts(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_DelCollProducts) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                var userid = comrcv.Map_Args["userid"];
                var ids = comrcv.Map_Args["ids"].Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);

                int num = mainsql.SqlExcuteNoReturn($"Delete from {BIAOBUYERCOLLPRODUCT} where user_id='{userid}' and prd_coll_id in('{string.Join("','", ids)}')");

                if (num > 0)
                {
                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    ret.Byte_Flag = (sbyte)1;
                }
                else
                {
                    ret.Map_Args["ErrorMsg"] = "操作失败";
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

            mainsql.closesql();
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 批量删除收藏的店铺
        [WebMethod(Description = "批量删除收藏的店铺")]
        public string Shop_DelCollShops(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_DelCollShops) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"];
                    var ids = comrcv.Map_Args["ids"].Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);

                    mainsql.SqlExcuteNoReturn($"Delete from {BIAOBUYERCOLLSHOP} where user_id='{userid}' and shop_id in('{string.Join("','", ids)}')");

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 输入用户手机号，匹配用户信息
        [WebMethod(Description = "输入用户手机号，匹配用户信息")]
        public string Shop_FindUserByPhone(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_FindUserByPhone) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var adduser = comrcv.Map_Args["user_phone"];
                    var model = mainsql.SqlExcuteWithReturn($"select user_onlyid,user_name from {BIAOUSER} where user_phone='{adduser}'").ToModels().FirstOrDefault();
                    if (model == null)
                    {
                        ret.Map_Args["ErrorMsg"] = "用户不存在";
                        mainsql.closesql();
                        goto EXIT;
                    }

                    ret.Map_Args.Add("user_id", model["user_onlyid"]);
                    ret.Map_Args.Add("user_name", model["user_name"]);
                    ret.Map_Args.Add("user_phone", adduser);

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 开关消息通知
        [WebMethod(Description = "开关消息通知")]
        public string Shop_BuyerEditMsg(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_BuyerEditMsg) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userid"];
                    var isOpen = comrcv.Map_Args["IsOpen"].ToInt32();//0关1开

                    var number = mainsql.SqlExecuteScalar($"update {BIAOUSER} set user_ismsg={isOpen} where user_onlyid='{userId}'");

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #endregion

        #region 留言
        private const string BIAOMSG = "s_chatrecord";

        #region 专属客户列表
        public string Shop_CustomerList(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_CustomerList) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var shopId = comrcv.Map_Args["shopId"];//店铺ID

                    if (string.IsNullOrWhiteSpace(shopId))
                    {
                        ret.Byte_Flag = -1;
                        ret.Map_Args["ErrorMsg"] = "缺少接口参数,shopId不能为空";
                        goto EXIT;
                    }

                    //查询店铺关联的用户，排除不是平台客服  user_customer_type=1
                    var users = mainsql.SqlExcuteWithReturn($@"
                    select b.* from  s_shopuser a 
                    right join {BIAOUSER} b on a.user_id=b.user_onlyid 
                    where a.shop_id='{shopId}' 
                    and user_customer_type=1").ToModels();

                    ret.Maplist_MapArgs.Add("Datas", users);
                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 客户留言
        [WebMethod(Description = "客户留言")]
        public string Shop_CustomerMessage(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_CustomerMessage) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userId = comrcv.Map_Args["userId"];//发送者
                    var shopId = ConfigurationManager.AppSettings["SystemMsg"].ToString();//接收者
                    var fileIds = comrcv.Map_Args["files"];//图片地址
                    var content = comrcv.Map_Args["Content"];//留言内容
                    var jsonStr = comrcv.Map_Args["JsonString"];

                    //如果有附件图片，转成永久
                    if (!string.IsNullOrWhiteSpace(fileIds))
                        ConvertTemporary(mainsql, fileIds);

                    //添加留言记录
                    var paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@ShopId", shopId));
                    paras.Add(new MySqlParameter("@FromUserId", userId));
                    paras.Add(new MySqlParameter("@Content", content));
                    paras.Add(new MySqlParameter("@imgFileId", fileIds.Trim(',')));
                    paras.Add(new MySqlParameter("@JsonString", jsonStr));

                    var id = mainsql.SqlExecuteScalar($"insert into {BIAOMSG}(shop_id,chart_isbuyer,user_id,chart_from_user_id,chart_content,chart_img_id,chart_json,chart_send_time,chart_isread)values"
                        + "(@ShopId,0,@FromUserId,@FromUserId,@Content,@imgFileId,@JsonString,NOW(),0);SELECT @@IDENTITY", paras.ToArray()).ToString();
                    ret.Map_Args.Add("MsgId", id);

                    mainsql.SqlExcuteNoReturn($"update {BIAOMSG} set chart_isread=1,chart_read_user_id='{userId}' where shop_id='{shopId}' and chart_isread=0 and chart_isbuyer=1 and user_id='{userId}'");

                    #region 发微信消息
                    var users = mainsql.SqlExcuteWithReturn($"select * from {BIAOUSER} where user_customer_type=1").ToModels();//取出平台客服
                    var user = mainsql.SqlExcuteWithReturn($"select * from {BIAOUSER} where user_onlyid='{userId}'").ToModels();//发送人

                    foreach (var item in users)
                    {
                        var openid = item["user_openid_juhesheng"];
                        if (!string.IsNullOrWhiteSpace(openid))
                        {
                            //发送消息
                            WebServiceShopping.wechartTools.SendMsg(new WebServiceShopping.wechartTools.ConsultantMsg()
                            {
                                miniprogram = new WebServiceShopping.wechartTools.XCXPath()
                                {
                                    pagepath = "pages/my/msg1/msg"
                                },
                                touser = openid,
                                data = new WebServiceShopping.wechartTools.ConsultantMsg.DataModel()
                                {
                                    keyword1 = new WebServiceShopping.wechartTools.DataItem()
                                    {
                                        value = user[0]["user_name"]
                                    },
                                    keyword2 = new WebServiceShopping.wechartTools.DataItem()
                                    {
                                        value = user[0]["user_phone"]
                                    },
                                    keyword3 = new WebServiceShopping.wechartTools.DataItem()
                                    {
                                        value = DateTime.Now.ToString("yyyy年MM月dd HH:mm:ss")
                                    }
                                }
                            });
                        }
                    }
                    #endregion

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 客户留言列表
        [WebMethod(Description = "客户留言列表")]
        public string Shop_CustomerMsgList(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_CustomerMessage) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var page = 1;//当前页
                    var limit = 20;//页容量
                    int.TryParse(comrcv.Map_Args["page"], out page);//当前页
                    int.TryParse(comrcv.Map_Args["limit"], out limit);//页容量
                    var shopIdSystem = ConfigurationManager.AppSettings["SystemMsg"].ToString();
                    StringBuilder sqlWhere = new StringBuilder();
                    int count = 0;
                    var result = new List<Dictionary<string, string>>();
                    var data = new List<Dictionary<string, string>>();

                    sqlWhere.AppendFormat(" order by chart_send_time desc");
                    var sql = $"select t1.*,t2.user_name,t2.user_phone,t4.file_path from s_chatrecord t1  left join {BIAOUSER} t2 on t1.user_id = t2.user_onlyid left join s_files t4 on t1.chart_img_id = t4.file_id where t1.shop_id = '{shopIdSystem}' {sqlWhere}";
                    data = mainsql.SqlExcuteWithReturn(sql).ToModels();

                    foreach (var item in data.GroupBy(t => t["user_id"]))
                    {
                        var itemSub = item.FirstOrDefault(t => t["chart_isread"].Equals("0"));

                        if (itemSub != null)
                        {
                            itemSub["count"] = item.Where(t => t["chart_isread"].Equals("0"))?.Count().ToString();
                        }
                        else
                        {

                            itemSub = item.ToList()[0];
                            itemSub["count"] = "0";
                        }

                        result.Add(itemSub);
                    }

                    count = result.Count();
                    result = result.Skip((page - 1) * limit).Take(limit).ToList();
                    ret.Map_Args["ErrorMsg"] = "操作成功";

                    ret.Map_Args.Add("Count", count.ToString());
                    ret.Maplist_MapArgs.Add("Data", result);
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 某一客户留言详情
        [WebMethod(Description = "某一客户留言详情")]
        public string Shop_CustomerMsgDetails(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_CustomerMsgDetails) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var page = 0;//当前页
                    var limit = 0;//页容量
                    var shopIdSystem = ConfigurationManager.AppSettings["SystemMsg"].ToString();
                    string shopId = shopIdSystem;
                    string userId = string.Empty;
                    string loginUserId = string.Empty;
                    string backstage = string.Empty;
                    int.TryParse(comrcv.Map_Args["page"], out page);//当前页
                    int.TryParse(comrcv.Map_Args["limit"], out limit);//页容量
                    StringBuilder sqlWhere = new StringBuilder();
                    int count = 0;
                    var result = new List<Dictionary<string, string>>();
                    var data = new List<Dictionary<string, string>>();

                    if (comrcv.Map_Args.Keys.Contains("userId"))
                    {
                        userId = comrcv.Map_Args["userId"];//当前消息的OnlyID
                    }
                    if (comrcv.Map_Args.Keys.Contains("loginUserId"))
                    {
                        loginUserId = comrcv.Map_Args["loginUserId"];//登录用户的OnlyID
                    }
                    if (comrcv.Map_Args.Keys.Contains("backstage"))
                    {
                        backstage = comrcv.Map_Args["backstage"];//当前消息的OnlyID
                    }

                    if (string.IsNullOrWhiteSpace(userId))
                    {
                        ret.Map_Args["ErrorMsg"] = "操作失败，未传入用户OnlyID";
                        goto EXIT;
                    }
                    if (string.IsNullOrWhiteSpace(loginUserId))
                    {
                        ret.Map_Args["ErrorMsg"] = "操作失败，未传入登录用户OnlyID";
                        goto EXIT;
                    }

                    string sql = $"select count(1) from s_chatrecord t1 left join {BIAOUSER} t2 on t1.user_id = t2.user_onlyid left join s_files t4 on t1.chart_img_id = t4.file_id where(t1.shop_id = '{shopId}' and t1.user_id ='{userId}') or (t1.shop_id ='{userId}' and t1.user_id = '{shopId}') {sqlWhere}";
                    count = mainsql.SqlExecuteScalar(sql).ToInt32();

                    sqlWhere.AppendFormat(" order by chart_send_time desc limit {0},{1}", limit * page - limit, limit);
                    sql = $@"
                    select CONCAT(t3.user_name,t3.user_phone) as sendUserName,t1.*,t2.user_name,t2.user_phone,t4.file_path from s_chatrecord t1 
                    left join {BIAOUSER} t2 on t1.user_id = t2.user_onlyid 
                    left join {BIAOUSER} t3 on t1.chart_from_user_id = t3.user_onlyid  
                    left join s_files t4 on t1.chart_img_id = t4.file_id
                    where(t1.shop_id = '{shopId}' and t1.user_id ='{userId}') or (t1.shop_id ='{userId}' and t1.user_id = '{shopId}') {sqlWhere}";
                    result = mainsql.SqlExcuteWithReturn(sql).ToModels();

                    var ids = string.Join(",", result.Where(x => !string.IsNullOrWhiteSpace(x["chart_img_id"])).Select(x => x["chart_img_id"])).Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                    if (ids.Length > 0)
                    {
                        var files = mainsql.SqlExcuteWithReturn($"select file_id,file_path from {BIAOSHOPFILE} where file_id in('{string.Join("','", ids)}')").ToModels();
                        ret.Maplist_MapArgs.Add("Files", files);
                    }

                    //后台查看
                    if (backstage.Equals("1"))
                    {
                        mainsql.SqlExcuteNoReturn($"update s_chatrecord set chart_isread=1,chart_read_user_id='{loginUserId}' where shop_id='{shopId}' and chart_isread=0 and chart_isbuyer=0 and user_id='{userId}'");
                    }
                    //首页查看
                    else
                    {
                        mainsql.SqlExcuteNoReturn($"update s_chatrecord set chart_isread=1,chart_read_user_id='{loginUserId}' where shop_id='{userId}' and chart_isread=0 and chart_isbuyer=1 and user_id='{shopId}'");
                    }

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    ret.Map_Args.Add("Count", count.ToString());//总条数
                    ret.Map_Args.Add("systemId", shopIdSystem);//平台
                    ret.Maplist_MapArgs.Add("Data", result);//数据
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 回复留言
        [WebMethod(Description = "回复留言")]
        public string Shop_AddChatCustome(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_AddChatCustome) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    string shopId = string.Empty;
                    string userId = string.Empty;
                    string loginUserId = string.Empty;
                    var content = comrcv.Map_Args["Content"];//留言内容
                    var jsonStr = comrcv.Map_Args["JsonString"];
                    var shopIdSystem = ConfigurationManager.AppSettings["SystemMsg"].ToString();

                    if (comrcv.Map_Args.Keys.Contains("loginUserId"))
                    {
                        loginUserId = comrcv.Map_Args["loginUserId"];//登录用户OnlyID
                    }
                    if (comrcv.Map_Args.Keys.Contains("userId"))
                    {
                        userId = comrcv.Map_Args["userId"];//当前消息的OnlyID
                    }
                    if (comrcv.Map_Args.Keys.Contains("shopId"))
                    {
                        shopId = comrcv.Map_Args["shopId"];//当前消息的店铺ID
                    }
                    if (comrcv.Map_Args.Keys.Contains("loginUserId"))
                    {
                        loginUserId = comrcv.Map_Args["loginUserId"];//登录用户OnlyID
                    }

                    if (string.IsNullOrWhiteSpace(loginUserId))
                    {
                        ret.Map_Args["ErrorMsg"] = "操作失败，未传入登录用户OnlyID";
                        goto EXIT;
                    }
                    if (string.IsNullOrWhiteSpace(userId))
                    {
                        ret.Map_Args["ErrorMsg"] = "操作失败，未传入用户OnlyID";
                        goto EXIT;
                    }
                    if (string.IsNullOrWhiteSpace(shopId))
                    {
                        ret.Map_Args["ErrorMsg"] = "操作失败，未传入店铺ID";
                        goto EXIT;
                    }

                    //添加留言
                    var paras = new List<MySqlParameter>();

                    paras.Add(new MySqlParameter("@ShopId", userId));
                    paras.Add(new MySqlParameter("@LoginUserId", loginUserId));
                    paras.Add(new MySqlParameter("@FromUserId", shopIdSystem));
                    paras.Add(new MySqlParameter("@Content", content));
                    paras.Add(new MySqlParameter("@JsonString", jsonStr));

                    if (comrcv.Map_Args.Keys.Contains("files"))
                    {
                        var fileIds = comrcv.Map_Args["files"];//图片地址
                        paras.Add(new MySqlParameter("@imgFileId", fileIds.Trim(',')));

                        //如果有附件图片，转成永久
                        if (!string.IsNullOrWhiteSpace(fileIds))
                            ConvertTemporary(mainsql, fileIds);
                    }
                    else
                    {
                        paras.Add(new MySqlParameter("@imgFileId", ""));
                    }

                    var id = mainsql.SqlExecuteScalar($"insert into s_chatrecord(shop_id,chart_isbuyer,user_id,chart_from_user_id,chart_content,chart_img_id,chart_json,chart_send_time,chart_isread)values"
                        + "(@ShopId,1,@FromUserId,@LoginUserId,@Content,@imgFileId,@JsonString,NOW(),0);SELECT @@IDENTITY", paras.ToArray()).ToString();

                    mainsql.SqlExcuteNoReturn($"update {BIAOMSG} set chart_isread=1,chart_read_user_id='{userId}' where shop_id='{shopId}' and chart_isread=0 and chart_isbuyer=1 and user_id='{userId}'");

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    ret.Map_Args.Add("MsgId", id);
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 留言详情列表
        [WebMethod(Description = "留言详情列表")]
        public string Shop_MsgList(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_MsgList) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"];
                    var shopId = comrcv.Map_Args["ShopId"];
                    var fromuserid = comrcv.Map_Args["FromUserId"];
                    var isbuyer = comrcv.Map_Args.ContainsKey("isbuyer") ? comrcv.Map_Args["isbuyer"].ToBool() : userid == fromuserid;

                    var msgid = comrcv.Map_Args.ContainsKey("id") ? comrcv.Map_Args["id"] : string.Empty;


                    var list = mainsql.SqlExcuteWithReturn($"select t1.*,t2.user_name,t2.user_phone from {BIAOMSG} t1 left join {BIAOUSER} t2 on t1.chart_from_user_id=t2.user_onlyid where t1.shop_id='{shopId}' and t1.user_id='{fromuserid}' {(string.IsNullOrWhiteSpace(msgid) ? "" : " and chart_id<" + msgid)} order by chart_send_time desc limit 0,20 ").ToModels();

                    if (string.IsNullOrWhiteSpace(msgid))
                    {
                        var time = DateTime.Now;
                        var result = new List<Dictionary<string, string>>();
                        foreach (var item in list)
                        {
                            result.Add(item);
                            if (time.Subtract(item["chart_send_time"].ToDateTime().Value).TotalHours > 2)
                            {
                                break;
                            }
                        }

                        ret.Map_Args.Add("allcount", list.Count.ToString());
                        list = result;
                    }

                    ret.Maplist_MapArgs.Add("Datas", list);

                    var ids = string.Join(",", list.Where(x => !string.IsNullOrWhiteSpace(x["chart_img_id"])).Select(x => x["chart_img_id"])).Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                    if (ids.Length > 0)
                    {
                        var files = mainsql.SqlExcuteWithReturn($"select file_id,file_path from {BIAOSHOPFILE} where file_id in('{string.Join("','", ids)}')").ToModels();
                        ret.Maplist_MapArgs.Add("Files", files);
                    }

                    //内容标记已读
                    if (isbuyer)
                    {//买家查看
                        mainsql.SqlExcuteNoReturn($"update {BIAOMSG} set chart_isread=1,chart_read_user_id='{userid}' where shop_id='{shopId}' and chart_isread=0 and chart_isbuyer=1 and user_id='{fromuserid}'");
                    }
                    else
                    {//卖家查看
                        mainsql.SqlExcuteNoReturn($"update {BIAOMSG} set chart_isread=1,chart_read_user_id='{userid}' where shop_id='{shopId}' and chart_isread=0 and chart_isbuyer=0 and user_id='{fromuserid}'");
                    }

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 卖家用户列表
        [WebMethod(Description = "卖家用户列表")]
        public string Shop_MsgUserList(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_MsgUserList) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var shopId = comrcv.Map_Args["ShopId"];
                    //查询店铺内，有哪些买家给我发送过留言，未回复的在前面
                    var list = mainsql.SqlExcuteWithReturn($"select t1.*,t3.user_phone,t3.user_name,t4.user_companyname from {BIAOMSG} t1 inner join (select max(chart_id) ID from {BIAOMSG} where shop_id='{shopId}' group by user_id) t2 "
                        + $" on t1.chart_id=t2.ID left join {BIAOUSER} t3 on t1.user_id=t3.user_onlyid left join {BIAOUSERCOMPANY} t4 on t1.user_id=t4.user_id order by t1.chart_isread").ToModels();
                    ret.Maplist_MapArgs.Add("Datas", list);

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 卖家回复留言
        [WebMethod(Description = "卖家回复留言")]
        public string Shop_MsgShopSend(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_MsgShopSend) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"];
                    var fromuserid = comrcv.Map_Args["FromUserId"];
                    var shopId = comrcv.Map_Args["ShopId"];
                    var fileIds = comrcv.Map_Args["files"];
                    var content = comrcv.Map_Args["Content"];
                    var jsonStr = comrcv.Map_Args["JsonString"];
                    //如果有附件图片，转成永久
                    if (!string.IsNullOrWhiteSpace(fileIds))
                        ConvertTemporary(mainsql, fileIds);

                    //var maxtime = mainsql.SqlExecuteScalar($"select max(chart_send_time) from {BIAOMSG} where shop_id='{shopId}' and user_id='{fromuserid}'").ToDateTime();

                    //添加回复记录
                    var paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@ShopId", shopId));
                    paras.Add(new MySqlParameter("@userid", fromuserid));
                    paras.Add(new MySqlParameter("@FromUserId", userid));
                    paras.Add(new MySqlParameter("@Content", content));
                    paras.Add(new MySqlParameter("@imgFileId", fileIds.Trim(',')));
                    paras.Add(new MySqlParameter("@JsonString", jsonStr));
                    var id = mainsql.SqlExecuteScalar($"insert into {BIAOMSG}(shop_id,chart_isbuyer,user_id,chart_from_user_id,chart_content,chart_img_id,chart_json,chart_send_time,chart_isread)values"
                        + "(@ShopId,1,@userid,@FromUserId,@Content,@imgFileId,@JsonString,NOW(),0);SELECT @@IDENTITY", paras.ToArray()).ToString();
                    ret.Map_Args.Add("MsgId", id);

                    mainsql.SqlExcuteNoReturn($"update {BIAOMSG} set chart_isread=1,chart_read_user_id='{userid}' where shop_id='{shopId}' and chart_isread=0 and chart_isbuyer=0 and user_id='{fromuserid}'");

                    #region 发微信消息
                    //if (maxtime.HasValue && maxtime.Value.AddHours(1) < DateTime.Now)
                    {
                        var shopMode = mainsql.SqlExcuteWithReturn($"select shop_name,shop_tel_number from {BIAOSHOP} where shop_id='{shopId}'").ToModels().FirstOrDefault();
                        var userModel = mainsql.SqlExcuteWithReturn($"select user_openid_juhesheng from {BIAOUSER} where user_onlyid='{fromuserid}' and user_ismsg='1'").ToModels();
                        foreach (var uitem in userModel)
                        {
                            var openid = uitem["user_openid_juhesheng"];
                            if (!string.IsNullOrWhiteSpace(openid))
                            {
                                //发送消息
                                WebServiceShopping.wechartTools.SendMsgGZH(new WebServiceShopping.wechartTools.ConsultantMsg()
                                {
                                    miniprogram = new WebServiceShopping.wechartTools.XCXPath()
                                    {
                                        pagepath = "/pages/my/msg/msg"
                                    },
                                    touser = openid,
                                    data = new WebServiceShopping.wechartTools.ConsultantMsg.DataModel()
                                    {
                                        keyword1 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = shopMode["shop_name"]
                                        },
                                        keyword2 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = shopMode["shop_tel_number"]
                                        },
                                        keyword3 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = DateTime.Now.ToString("yyyy年MM月dd HH:mm")
                                        },
                                        remark = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = content
                                        }
                                    }
                                });
                            }
                        }
                    }
                    #endregion

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 买家店铺列表
        [WebMethod(Description = "买家店铺列表")]
        public string Shop_MsgShopList(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_MsgShopList) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"];
                    //查询买家给哪些店铺发送过留言，按最新时间排序（最新发送时间和回复时间）
                    var list = mainsql.SqlExcuteWithReturn($"select t1.*,t3.shop_name as ShopName,t4.file_small_path as ShopTitlePath from {BIAOMSG} t1 inner join (select max(chart_id) ID from {BIAOMSG} where user_id='{userid}' group by shop_id) t2 "
                        + $" on t1.chart_id=t2.ID left join {BIAOSHOP} t3 on t1.shop_id=t3.shop_id left join {BIAOSHOPFILE} t4 on t3.shop_title_id=t4.file_id order by t1.chart_send_time desc").ToModels();
                    ret.Maplist_MapArgs.Add("Datas", list);

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 买家发送留言
        [WebMethod(Description = "买家发送留言")]
        public string Shop_MsgUserSend(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_MsgUserSend) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"];
                    var shopId = comrcv.Map_Args["ShopId"];
                    var fileIds = comrcv.Map_Args["files"];
                    var content = comrcv.Map_Args["Content"];
                    var jsonStr = comrcv.Map_Args["JsonString"];
                    //var maxTime = mainsql.SqlExecuteScalar($"select max(chart_send_time) from {BIAOMSG} where shop_id='{shopId}' and user_id='{userid}'").ToDateTime();
                    //if (!maxTime.HasValue || maxTime.Value.AddHours(12) <= DateTime.Now)
                    {
                        var model = mainsql.SqlExcuteWithReturn($"select shop_name,shop_tel_number,shop_tel_number2 from {BIAOSHOP} where shop_id='{shopId}'").ToModels().FirstOrDefault();
                        if (model != null)
                        {
                            var phone = model["shop_tel_number"];
                            var shopName = model["shop_name"];

                            ILog logJieKou = LogManager.GetLogger("LoggerJieKou");

                            //if (!string.IsNullOrWhiteSpace(phone))
                            //{
                            //    var i = SmsSendInterface.sendOnce(phone, "尊敬的（" + shopName + "）商户您好，您的店铺有一条新的消息，请尽快进入青贯助手小程序查看回复。");

                            //    logJieKou.Info($"发送消息短信：{phone} 返回结果：{i}");
                            //}
                            //else
                            //{
                            //    logJieKou.Info($"发送消息短信：没有号码");
                            //}

                            #region 发微信消息
                            var userModel = mainsql.SqlExcuteWithReturn($"select user_name,user_phone from {BIAOUSER} where user_onlyid='{userid}'").ToModels().FirstOrDefault();
                            phone = userModel["user_phone"];
                            var name = userModel["user_name"];
                            var users = mainsql.SqlExcuteWithReturn($"select t2.user_openid_juhesheng,t1.user_id from {BIAOSHOPUSER} t1 left join {BIAOUSER} t2 on t1.user_id=t2.user_onlyid where shop_id='{shopId}' and shop_user_ismsg=1 and shop_user_deleteflag<>1").ToModels();
                            foreach (var uitem in users)
                            {
                                var openid = uitem["user_openid_juhesheng"];
                                if (!string.IsNullOrWhiteSpace(openid))
                                {
                                    //发送消息
                                    WebServiceShopping.wechartTools.SendMsgGZH(new WebServiceShopping.wechartTools.ConsultantMsg()
                                    {
                                        miniprogram = new WebServiceShopping.wechartTools.XCXPath()
                                        {
                                            pagepath = "/pages/my/store/store?ShopId=" + shopId
                                        },
                                        touser = openid,
                                        data = new WebServiceShopping.wechartTools.ConsultantMsg.DataModel()
                                        {
                                            keyword1 = new WebServiceShopping.wechartTools.DataItem()
                                            {
                                                value = name
                                            },
                                            keyword2 = new WebServiceShopping.wechartTools.DataItem()
                                            {
                                                value = phone
                                            },
                                            keyword3 = new WebServiceShopping.wechartTools.DataItem()
                                            {
                                                value = DateTime.Now.ToString("yyyy年MM月dd HH:mm")
                                            },
                                            remark = new WebServiceShopping.wechartTools.DataItem()
                                            {
                                                value = content
                                            }
                                        }
                                    });
                                }
                            }
                            #endregion
                        }
                    }
                    //如果有附件图片，转成永久
                    if (!string.IsNullOrWhiteSpace(fileIds))
                        ConvertTemporary(mainsql, fileIds);
                    //添加留言记录
                    var paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@ShopId", shopId));
                    paras.Add(new MySqlParameter("@FromUserId", userid));
                    paras.Add(new MySqlParameter("@Content", content));
                    paras.Add(new MySqlParameter("@imgFileId", fileIds.Trim(',')));
                    paras.Add(new MySqlParameter("@JsonString", jsonStr));
                    var id = mainsql.SqlExecuteScalar($"insert into {BIAOMSG}(shop_id,chart_isbuyer,user_id,chart_from_user_id,chart_content,chart_img_id,chart_json,chart_send_time,chart_isread)values"
                        + "(@ShopId,0,@FromUserId,@FromUserId,@Content,@imgFileId,@JsonString,NOW(),0);SELECT @@IDENTITY", paras.ToArray()).ToString();
                    ret.Map_Args.Add("MsgId", id);

                    mainsql.SqlExcuteNoReturn($"update {BIAOMSG} set chart_isread=1,chart_read_user_id='{userid}' where shop_id='{shopId}' and chart_isread=0 and chart_isbuyer=1 and user_id='{userid}'");

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 店铺he修理厂相互留言

        #region 店铺或修理厂发送留言
        [WebMethod(Description = "店铺或修理厂发送留言")]
        public string Shop_ShopOrRepairSendMsg(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_ShopOrRepairSendMsg) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
            mysqlcli mainsql = new mysqlcli();

            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var shopId = comrcv.Map_Args["shopId"];//店铺ID
                    var repairId = comrcv.Map_Args["repairId"];//修理厂ID
                    var fileIds = comrcv.Map_Args["files"];
                    var content = comrcv.Map_Args["Content"];
                    var jsonStr = comrcv.Map_Args["JsonString"];
                    var isbuyer = comrcv.Map_Args["chart_isbuyer"];//2店铺，3修理厂
                    var userId = comrcv.Map_Args["userId"];//当前登录用户

                    //var shopId = "032b5df9-5fe8-44a4-b741-bce940dcc15c";//店铺ID
                    //var repairId = "343b1bcc-17db-4ff3-9101-805655bae6e8";//修理厂ID
                    //var userId = "343b1bcc-17db-4ff3-9101-805655bae6e8";//修理厂ID
                    //var fileIds = string.Empty;
                    //var content = "测试-------------";
                    //var jsonStr = string.Empty;
                    //var isbuyer = "3";

                    //添加留言记录
                    var paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@Content", content));
                    paras.Add(new MySqlParameter("@imgFileId", fileIds.Trim(',')));
                    paras.Add(new MySqlParameter("@JsonString", jsonStr));
                    paras.Add(new MySqlParameter("@isbuyer", isbuyer));
                    paras.Add(new MySqlParameter("@FromUserId", userId));//谁发送的

                    var phone = string.Empty;
                    var name = string.Empty;
                    var users = new List<Dictionary<string, string>>();
                    var pagepath = string.Empty;

                    //店铺
                    if (isbuyer.Equals("2"))
                    {
                        pagepath = "pages/my/msgxlcshop/msg?xlcid=" + repairId;

                        paras.Add(new MySqlParameter("@ShopId", shopId));//发送人
                        paras.Add(new MySqlParameter("@UserId", repairId));//接收人

                        //获取店铺信息
                        var model = mainsql.SqlExcuteWithReturn($"select shop_name,shop_tel_number,shop_tel_number2 from {BIAOSHOP} where shop_id='{shopId}'").ToModels().FirstOrDefault();

                        phone = model["shop_tel_number"];
                        name = model["shop_name"];

                        //获取店铺关联用户
                        var sql = $"select b.* from {BIAOSHOPUSER} a inner join {BIAOUSER} b  on a.user_id=b.user_onlyid where shop_id='{shopId}'";
                        users = mainsql.SqlExcuteWithReturn(sql).ToModels();
                    }

                    //修理厂
                    else if (isbuyer.Equals("3"))
                    {
                        pagepath = "pages/my/msgxlcshop/msg?shopid=" + shopId;

                        paras.Add(new MySqlParameter("@ShopId", repairId));//发送人
                        paras.Add(new MySqlParameter("@UserId", shopId));//接收人

                        //获取修理厂信息
                        var model = mainsql.SqlExcuteWithReturn($"select* from s_usercompany where user_id ='{repairId}'").ToModels().FirstOrDefault();

                        phone = model["user_companytel"];
                        name = model["user_companyname"];

                        var userPhone = model["user_binduserid"].Trim(',');
                        userPhone = string.Join("','", userPhone.Split(','));

                        //获取店铺关联用户
                        var sql = $"select* from {BIAOUSER} where user_phone in ('{userPhone}')";
                        users = mainsql.SqlExcuteWithReturn(sql).ToModels();
                    }
                    else
                    {
                        ret.Map_Args["ErrorMsg"] = "未传入正确的参数[chart_isbuyer]";  //参数错误
                        goto EXIT;
                    }

                    #region 发微信消息

                    foreach (var uitem in users)
                    {
                        var openid = uitem["user_openid_juhesheng"];
                        if (!string.IsNullOrWhiteSpace(openid))
                        {
                            //发送消息
                            WebServiceShopping.wechartTools.SendMsgGZH(new WebServiceShopping.wechartTools.ConsultantMsg()
                            {
                                miniprogram = new WebServiceShopping.wechartTools.XCXPath()
                                {
                                    pagepath = pagepath
                                },
                                touser = openid,
                                data = new WebServiceShopping.wechartTools.ConsultantMsg.DataModel()
                                {
                                    keyword1 = new WebServiceShopping.wechartTools.DataItem()
                                    {
                                        value = name
                                    },
                                    keyword2 = new WebServiceShopping.wechartTools.DataItem()
                                    {
                                        value = phone
                                    },
                                    keyword3 = new WebServiceShopping.wechartTools.DataItem()
                                    {
                                        value = DateTime.Now.ToString("yyyy年MM月dd HH:mm")
                                    },
                                    remark = new WebServiceShopping.wechartTools.DataItem()
                                    {
                                        value = content
                                    }
                                }
                            });
                        }
                    }

                    #endregion

                    //如果有附件图片，转成永久
                    if (!string.IsNullOrWhiteSpace(fileIds))
                        ConvertTemporary(mainsql, fileIds);


                    var id = mainsql.SqlExecuteScalar($@"insert into {BIAOMSG}(
                                                        shop_id,
                                                        chart_isbuyer,
                                                        user_id,
                                                        chart_from_user_id,
                                                        chart_content,
                                                        chart_img_id,
                                                        chart_json,
                                                        chart_send_time,
                                                        chart_isread)values (
                                                        @ShopId,
                                                        @isbuyer,
                                                        @UserId,
                                                        @FromUserId,
                                                        @Content,
                                                        @imgFileId,
                                                        @JsonString,
                                                        NOW(),
                                                        0);SELECT @@IDENTITY", paras.ToArray()).ToString();

                    ret.Map_Args.Add("MsgId", id);

                    //mainsql.SqlExcuteNoReturn($"update {BIAOMSG} set chart_isread=1,chart_read_user_id='{repairId}' where shop_id='{shopId}' and chart_isread=0 and chart_isbuyer=1 and user_id='{repairId}'");

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 店铺或修理厂留言列表
        [WebMethod(Description = "店铺或修理厂留言列表")]
        public string Get_ShopOrRepairMsgList(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Get_ShopOrRepairMsgList) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var page = 1;//当前页
                    var limit = 20;//页容量
                    int.TryParse(comrcv.Map_Args["page"], out page);//当前页
                    int.TryParse(comrcv.Map_Args["limit"], out limit);//页容量
                    var id = comrcv.Map_Args["id"];//当前店铺或修理场ID
                    var isbuyer = comrcv.Map_Args["isbuyer"];//2店铺，3修理厂


                    //var page = 1;//当前页
                    //var limit = 20;//页容量
                    ////var id = "032b5df9-5fe8-44a4-b741-bce940dcc15c";//当前修理场ID
                    //var id = "343b1bcc-17db-4ff3-9101-805655bae6e8";//当前店铺ID
                    //var isbuyer ="3";//2店铺，3修理厂


                    var sql = string.Empty;
                    Func<Dictionary<string, string>, string> func = null;

                    //店铺查看
                    if (isbuyer.Equals("2"))
                    {
                        loginfo.Info("22");
                        func = t => t["user_id"];
                        sql = $@"select a.*,b.user_companyname,b.user_id as companyId,c.* from s_chatrecord a
                                left JOIN s_usercompany b on a.shop_id=b.user_id 
                                left JOIN s_files c on b.user_mentou=c.file_id
                                where  a.user_id='{id}' and (chart_isbuyer='2'||chart_isbuyer='3') ORDER BY chart_send_time desc";
                    }
                    //修理查看
                    else if (isbuyer.Equals("3"))
                    {
                        loginfo.Info("33");
                        func = t => t["shop_id"];
                        sql = $@"select a.*,b.shop_name,b.shop_id as shopId,c.* from s_chatrecord a
                                left JOIN s_shop b on a.shop_id=b.shop_id 
                                left JOIN s_files c on b.shop_title_id=c.file_id
                                where  a.user_id='{id}' and (chart_isbuyer='2'||chart_isbuyer='3') ORDER BY chart_send_time desc";
                    }
                    else
                    {
                        ret.Map_Args["ErrorMsg"] = "未传入正确的参数[chart_isbuyer]";  //参数错误
                        goto EXIT;
                    }

                    loginfo.Info(sql);

                    int count = 0;
                    var result = new List<Dictionary<string, string>>();
                    var data = new List<Dictionary<string, string>>();
                    data = mainsql.SqlExcuteWithReturn(sql).ToModels();

                    var groupData = data.GroupBy(t => t["shop_id"]);

                    foreach (var item in groupData)
                    {
                        var itemSub = item.FirstOrDefault(t => t["chart_isread"].Equals("0"));

                        if (itemSub != null)
                        {
                            itemSub["count"] = item.Where(t => t["chart_isread"].Equals("0"))?.Count().ToString();
                        }
                        else
                        {

                            itemSub = item.ToList()[0];
                            itemSub["count"] = "0";
                        }

                        result.Add(itemSub);
                    }

                    count = result.Count();
                    result = result.Skip((page - 1) * limit).Take(limit).ToList();
                    ret.Map_Args["ErrorMsg"] = "操作成功";

                    ret.Map_Args.Add("Count", count.ToString());
                    ret.Maplist_MapArgs.Add("Data", result);
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 店铺或修理留言详情
        [WebMethod(Description = "店铺或修理留言详情")]
        public string Get_MsgDetails(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Get_MsgDetails) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var repairId = comrcv.Map_Args["repairId"];//修理厂ID
                    var shopId = comrcv.Map_Args["shopId"];//店铺厂ID
                    var isbuyer = comrcv.Map_Args["isbuyer"];//2店铺，3修理厂
                    var userId = comrcv.Map_Args["userId"];//登录用户

                    //var repairId = "343b1bcc-17db-4ff3-9101-805655bae6e8";//修理厂ID
                    //var shopId = "4a475def-e520-4ead-98f1-ce2813aa3964";//店铺厂ID
                    //var isbuyer = "2";//2店铺，3修理厂
                    //var userId = "9bce6fb1-4588-4b31-b57d-f58fc6e423a3";//2店铺，3修理厂

                    //内容标记已读
                    if (isbuyer.Equals("2"))
                    {
                        loginfo.Info($"2 update {BIAOMSG} set chart_isread=1,chart_read_user_id='{userId}' where shop_id='{shopId}' and chart_isread=0 and chart_isbuyer=3 and user_id='{repairId}'");
                        mainsql.SqlExcuteNoReturn($"update {BIAOMSG} set chart_isread=1,chart_read_user_id='{userId}' where shop_id='{shopId}' and chart_isread=0 and chart_isbuyer=3 and user_id='{repairId}'");
                    }
                    else if (isbuyer.Equals("3"))
                    {
                        loginfo.Info($" 3 update {BIAOMSG} set chart_isread=1,chart_read_user_id='{userId}' where shop_id='{shopId}' and chart_isread=0 and chart_isbuyer=2 and user_id='{repairId}'");
                        mainsql.SqlExcuteNoReturn($"update {BIAOMSG} set chart_isread=1,chart_read_user_id='{userId}' where shop_id='{shopId}' and chart_isread=0 and chart_isbuyer=2 and user_id='{repairId}'");
                    }
                    else
                    {
                        ret.Map_Args["ErrorMsg"] = "未传入正确的参数[chart_isbuyer]";  //参数错误
                        goto EXIT;
                    }

                    var msgid = comrcv.Map_Args.ContainsKey("id") ? comrcv.Map_Args["id"] : string.Empty;


                    var sql = $@"select d.user_name, b.user_companyname,c.shop_name,a.* from s_chatrecord a 
                                left join s_usercompany b on a.shop_id=b.user_id||a.user_id=b.user_id
                                left join s_shop c on a.shop_id=c.shop_id||a.user_id=c.shop_id
                                left join yonghualluser d on d.user_onlyid=a.chart_from_user_id
                                where  {(string.IsNullOrWhiteSpace(msgid) ? "1=1" : " and chart_id<" + msgid)}
                                and (a.shop_id = '{repairId}' and a.user_id ='{shopId}') 
                                or (a.shop_id ='{shopId}' and a.user_id = '{repairId}') order by chart_send_time desc limit 0,20";

                    var list = mainsql.SqlExcuteWithReturn(sql).ToModels();

                    if (string.IsNullOrWhiteSpace(msgid))
                    {
                        var time = DateTime.Now;
                        var result = new List<Dictionary<string, string>>();
                        foreach (var item in list)
                        {
                            result.Add(item);
                            if (time.Subtract(item["chart_send_time"].ToDateTime().Value).TotalHours > 2)
                            {
                                break;
                            }
                        }

                        ret.Map_Args.Add("allcount", list.Count.ToString());
                        list = result;
                    }

                    ret.Maplist_MapArgs.Add("Datas", list);

                    var ids = string.Join(",", list.Where(x => !string.IsNullOrWhiteSpace(x["chart_img_id"])).Select(x => x["chart_img_id"])).Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                    if (ids.Length > 0)
                    {
                        var files = mainsql.SqlExcuteWithReturn($"select file_id,file_path from {BIAOSHOPFILE} where file_id in('{string.Join("','", ids)}')").ToModels();
                        ret.Maplist_MapArgs.Add("Files", files);
                    }


                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion


        #endregion

        #region 买家未读消息数
        [WebMethod(Description = "买家未读消息数")]
        public string Shop_MsgUserReadCount(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_MsgUserReadCount) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"];
                    var count = mainsql.SqlExecuteScalar($"select count(1) from(select count(1) from {BIAOMSG} where user_id='{userid}' and chart_isbuyer=1 and chart_isread=0 group by shop_id) as tb").ToInt32();
                    ret.Map_Args.Add("count", count.ToString());

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 卖家未读消息数
        [WebMethod(Description = "卖家未读消息数")]
        public string Shop_MsgShopReadCount(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_MsgShopReadCount) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var shopId = comrcv.Map_Args["ShopId"];
                    var count = mainsql.SqlExecuteScalar($"select count(1) from(select user_id from {BIAOMSG} where shop_id='{shopId}' and chart_isbuyer=0 and chart_isread=0 group by user_id) as tb").ToInt32();
                    ret.Map_Args.Add("count", count.ToString());

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 删除留言列表
        [WebMethod(Description = "删除留言列表")]
        public string Shop_DelMsgList(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_DelMsgList) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    //var userid = comrcv.Map_Args["userid"];
                    var shopId = comrcv.Map_Args["ShopId"]; //店铺ID
                    var fromuserid = comrcv.Map_Args["FromUserId"]; //买家ID
                    var deleteflag = comrcv.Map_Args["DeleteFlag"].ToInt32(); //1买家删除店铺，2店铺删除买家

                    var model = mainsql.SqlExcuteWithReturn($"select chart_id,chart_deleteflag from {BIAOMSG} t1 inner join (select max(chart_id) as id from {BIAOMSG} where shop_id='{shopId}' and user_id='{fromuserid}') t2 on t1.chart_id=id").ToModels().FirstOrDefault();
                    if (model != null)
                    {
                        deleteflag = model["chart_deleteflag"].ToInt32() | deleteflag;
                        var msgId = model["chart_id"].ToLong();
                        mainsql.SqlExcuteNoReturn($"update {BIAOMSG} set chart_deleteflag={deleteflag} where chart_id={msgId}");

                        ret.Map_Args.Add("DeleteFlag", deleteflag.ToString());
                    }

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #endregion

        #region 团购商品

        #region 获取门店商品品类型列表
        [WebMethod(Description = "获取门店商品品类型列表")]
        public string Shop_GetCommodityTypeAll(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetCommodityTypeAll) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var sql = $@"select commpdity_type_name as name,commpdity_type_id as id from s_commpditytype where commpdity_type_status=1";

                    //获取指定的店铺产品
                    List<Dictionary<string, string>> dics = new List<Dictionary<string, string>>();
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    dic.Add("name", "全部");
                    dic.Add("id", "");
                    dics.Add(dic);

                    var commpditytypes = mainsql.SqlExcuteWithReturn(sql).ToModels();
                    dics = dics.Concat(commpditytypes).ToList();

                    ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
                    ret.Maplist_MapArgs.Add("Data", dics);
                    ret.Byte_Flag = (sbyte)1;

                    mainsql.closesql();
                    tsall.Complete();
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 获取指定门店商品列表
        [WebMethod(Description = "获取指定门店商品列表")]
        public string Shop_GetCommodityByCompanyId(string msg)
        {
            //string msg = "E9qotD7Joti3FcG8FavbjlDxDrpoqDbz9JbJCu+f/iF9S1LlxTHgKR2dawJ2/PhgQBg8rp/Zj93083t4Gh4wGOUuz4rdcJXu7Ptzu/hW+gbC1ji+DpPiCb/bY3YoejhdXKhy7/ZOZMxrwzy6zYP8CQiRvXObQ1tpmExaRvvpDPk70z49pZqojQi9WhcfF7U9zUFe/QqPpvf7cCVOlCVvxQ==";
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetCommodityByCompanyId) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var sql = $"select a.* from s_commodity a INNER join s_commpditytype b on a.commpdity_type_id = b.commpdity_type_id where a.commodity_isdel=0";
                    string yonghu_longitude = "";
                    string yonghu_latitude = "";
                    if (comrcv.Map_Args.ContainsKey("longitude"))//是否传定位进行查询
                    {
                        yonghu_longitude = comrcv.Map_Args["longitude"];
                        yonghu_latitude = comrcv.Map_Args["latitude"];
                        sql = $"select a.*,(select user_star from s_usercompany where user_id=a.company_id) as user_star,(select user_companyname from s_usercompany where user_id=a.company_id) as user_companyname,(select round( st_distance_sphere (point ({yonghu_longitude},{yonghu_latitude}),point (`user_longitude`,`user_latitude`)))  /1000 dis from  s_usercompany where user_id=a.company_id) as distance from s_commodity a INNER join s_commpditytype b on a.commpdity_type_id = b.commpdity_type_id where a.commodity_isdel=0";
                    }

                    //门店ID
                    if (comrcv.Map_Args.Keys.Contains("commodityName"))
                    {
                        var commodityName = comrcv.Map_Args["commodityName"];

                        if (!string.IsNullOrWhiteSpace(commodityName))
                        {
                            sql = $"{sql} and  a.commodity_name like '%{commodityName}%'";
                        }
                    }

                    //门店ID
                    if (comrcv.Map_Args.Keys.Contains("companyId"))
                    {
                        var companyId = comrcv.Map_Args["companyId"];

                        if (!string.IsNullOrWhiteSpace(companyId))
                        {
                            sql = $"{sql} and  a.company_id='{companyId}'";
                        }
                    }

                    //产品类型
                    if (comrcv.Map_Args.Keys.Contains("commpdityTypeId"))
                    {
                        var commpdityTypeId = comrcv.Map_Args["commpdityTypeId"];

                        if (!string.IsNullOrWhiteSpace(commpdityTypeId))
                        {
                            sql = $"{sql} and b.commpdity_type_id='{commpdityTypeId}'";
                        }
                    }

                    //产品状态
                    if (comrcv.Map_Args.Keys.Contains("status"))
                    {
                        var status = comrcv.Map_Args["status"];//0：禁用，1：启用

                        if (!string.IsNullOrWhiteSpace(status))
                        {
                            sql = $"{sql}  and a.commodity_status = {status}";
                        }
                    }
                    //排序字段
                    int sortType= 0;//排序类型,0全部，1距离，2价格，3评分
                    int sortAsc = 0;//排序方式 0升序，1降序
                    if (comrcv.Map_Args.Keys.Contains("sortType"))
                    {
                        sortType = Convert.ToInt32(comrcv.Map_Args["sortType"]);//排序类型
                        sortAsc = Convert.ToInt32(comrcv.Map_Args["sortAsc"]);//排序方式
                    }
                    string sortAscStr = sortAsc == 0 ? " asc " : " desc ";//排序方式字符化
                    string sqlSrot = ""; 
                    switch (sortType)
                    {
                        case 0://全部
                            sqlSrot = $"order by a.commodity_create_time {sortAscStr}";
                            break;
                        case 1://距离
                            sqlSrot = $"order by distance {sortAscStr}";
                            break;
                        case 2://价格
                            sqlSrot = $"order by a.commodity_actual_price {sortAscStr}"; ;
                            break;
                        case 3://评分
                            sqlSrot = $"order by user_star {sortAscStr}"; ;
                            break;
                        default:
                            break;
                    }





                    sql = $"{sql} {sqlSrot} ";
                    loginfo.Info(sql);

                    //获取指定的店铺产品
                    ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
                    var commpditys = mainsql.SqlExcuteWithReturn(sql).ToModels();

                    var ids = string.Join(",", commpditys.Where(x => !string.IsNullOrWhiteSpace(x["commodity_file_id"])).Select(x => x["commodity_file_id"])).Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);

                    loginfo.Info(ids);
                    if (ids.Length > 0)
                    {
                        var files = mainsql.SqlExcuteWithReturn($"select file_id,file_path from {BIAOSHOPFILE} where file_id in('{string.Join("','", ids)}')").ToModels();
                        loginfo.Info($"select file_id,file_path from {BIAOSHOPFILE} where file_id in('{string.Join("','", ids)}')");
                        ret.Maplist_MapArgs.Add("Files", files);
                    }
                    else
                    {
                        ret.Maplist_MapArgs.Add("Files", new List<Dictionary<string, string>>());
                    }

                    ret.Maplist_MapArgs.Add("Data", commpditys);
                    ret.Byte_Flag = (sbyte)1;

                    mainsql.closesql();
                    tsall.Complete();
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 添加门店商品
        [WebMethod(Description = "添加门店商品")]
        public string Shop_AddCommodity(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_AddCommodity) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var commodity_id = Guid.NewGuid().ToString();//商品ID
                    var commodity_status = 1;//商品状态：0未上架，1已上架，2未审核，3已审核
                    var userId = comrcv.Map_Args["userId"];//登录用户
                    var commodity_name = comrcv.Map_Args["commodityName"];//商品名称
                    var commodity_actual_price = comrcv.Map_Args["commodityActualPrice"];//商品实际价格
                    var commodity_original_price = comrcv.Map_Args["commodityOriginalPrice"];//商品原价
                    var commodity_content = comrcv.Map_Args["commodityContent"];//商品套餐内容
                    var commpdity_type_id = comrcv.Map_Args["commpdityTypeId"];//类型ID
                    var company_id = comrcv.Map_Args["companyId"];//门店ID
                    var fileIds = comrcv.Map_Args["files"];//图片地址
                    var commodity_content_text = string.Empty;

                    if (string.IsNullOrWhiteSpace(commodity_actual_price))
                    {
                        commodity_actual_price = commodity_original_price;
                    }

                    if (comrcv.Map_Args.Keys.Contains("commodityContentText"))//其他文本信息
                    {
                        commodity_content_text = comrcv.Map_Args["commodityContentText"];
                    }

                    if (comrcv.Map_Args.Keys.Contains("commodityId"))
                    {
                        commodity_id = comrcv.Map_Args["commodityId"];

                        if (string.IsNullOrWhiteSpace(commodity_id))
                        {
                            ret.Map_Args["ErrorMsg"] = "商品ID不能为空";  //参数错误
                            goto EXIT;
                        }
                    }

                    var paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@commodity_id", commodity_id));
                    paras.Add(new MySqlParameter("@commodity_status", commodity_status));
                    paras.Add(new MySqlParameter("@commodity_name", commodity_name));
                    paras.Add(new MySqlParameter("@commodity_actual_price", commodity_actual_price));
                    paras.Add(new MySqlParameter("@commodity_original_price", commodity_original_price));
                    paras.Add(new MySqlParameter("@commodity_content", commodity_content));
                    paras.Add(new MySqlParameter("@commpdity_type_id", commpdity_type_id));
                    paras.Add(new MySqlParameter("@commodity_content_text", commodity_content_text));
                    paras.Add(new MySqlParameter("@company_id", company_id));
                    paras.Add(new MySqlParameter("@fileIds", fileIds));
                    paras.Add(new MySqlParameter("@userId", userId));

                    //如果有附件图片，转成永久
                    if (!string.IsNullOrWhiteSpace(fileIds))
                        ConvertTemporary(mainsql, fileIds);

                    var message = "添加";
                    var sql = $@"insert into s_commodity (
                                    commodity_id,
                                    commodity_create_user,
                                    commodity_status,
                                    commodity_name,
                                    commodity_actual_price,
                                    commodity_original_price,
                                    commodity_content,
                                    commodity_content_text,
                                    commpdity_type_id,
                                    company_id,
                                    commodity_file_id,
                                    commodity_create_time
                                    )values(
                                    @commodity_id,
                                    @userId,
                                    @commodity_status,
                                    @commodity_name,
                                    @commodity_actual_price,
                                    @commodity_original_price,
                                    @commodity_content,
                                    @commodity_content_text,
                                    @commpdity_type_id,
                                    @company_id,
                                    @fileIds,
                                    NOW());";

                    if (comrcv.Map_Args.Keys.Contains("commodityId"))
                    {
                        message = "修改";
                        sql = $@"update s_commodity set
                                commodity_update_user=@userId,
                                commodity_status=@commodity_status,
                                commodity_name=@commodity_name,
                                commodity_actual_price=@commodity_actual_price,
                                commodity_original_price=@commodity_original_price,
                                commodity_content=@commodity_content,
                                commodity_content_text=@commodity_content_text,
                                commpdity_type_id=@commpdity_type_id,
                                company_id=@company_id,
                                commodity_file_id=@fileIds,
                                commodity_update_time=NOW()
                                where commodity_id=@commodity_id;";

                    }

                    loginfo.Info($"添加商品：{sql}");

                    var num = mainsql.SqlExcuteNoReturn(sql, paras.ToArray());

                    if (num > 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "操作成功";  //参数错误
                        ret.Byte_Flag = (sbyte)1;

                        #region 发微信消息
                        var usersWacht = mainsql.SqlExcuteWithReturn($"select * from yonghualluser where user_customer_type=1").ToModels();//取出平台客服

                        foreach (var item in usersWacht)
                        {
                            var openid = item["user_openid_juhesheng"];
                            if (!string.IsNullOrWhiteSpace(openid))
                            {
                                //发送消息
                                WebServiceShopping.wechartTools.SendMsgGZH(new WebServiceShopping.wechartTools.ToExamineMsg()
                                {
                                    miniprogram = new WebServiceShopping.wechartTools.XCXPath()
                                    {
                                        pagepath = ""
                                    },
                                    touser = openid,
                                    data = new WebServiceShopping.wechartTools.ToExamineMsg.DataModel()
                                    {
                                        first = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = $"您好，以下是您{message}的团购商品待审核信息！"
                                        },
                                        keyword1 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = "团购商品"
                                        },
                                        keyword2 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = commodity_name
                                        },
                                        keyword3 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = DateTime.Now.ToString("yyyy年MM月dd HH:mm:ss")
                                        },
                                        keyword4 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = "已上架"
                                        }
                                    }
                                });
                            }
                        }
                        #endregion
                    }

                    mainsql.closesql();
                    tsall.Complete();
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 获取指定门店商品详细
        [WebMethod(Description = "获取指定门店商品详细")]
        public string Shop_GetCommodityDetail(string msg)
        {

            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetCommodityDetail) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            //string sqlcmd = string.Format("select * from {0}202212 where zf_qgnumber = '{1}'; ",
            //    BIAOQGZHIFURECORD , "00000202212031432340007");

            //DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
            //var orders = ds.ToModels();
            //var orderIds = string.Join(",", orders.Select(x => x["zf_biaoid"]));
            //tuangou_huidiao(orderIds, "00000202212031432340007", true, loginfo);

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var commodityId = comrcv.Map_Args["commodityId"];//商品ID
                    var sql = $@"select a.*,b.* ,c.file_small_path as companyPath ,(SELECT count(1) from s_commodity where company_id=(select company_id from s_commodity where commodity_id = '{commodityId}' ) and  commodity_status<>0)as user_commodityAllNum from s_commodity a
                                left join s_usercompany b on a.company_id=b.user_id
                                left join s_files c on b.user_mentou =c.file_id
                                where commodity_id = '{commodityId}'";

                    //获取指定的店铺产品信息
                    var commodity = mainsql.SqlExcuteWithReturn(sql).ToModels().FirstOrDefault();

                    if (commodity != null)
                    {
                        if (!string.IsNullOrWhiteSpace(commodity["commodity_file_id"]))
                        {
                            var ids = commodity["commodity_file_id"].Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);

                            if (ids.Length > 0)
                            {
                                var files = mainsql.SqlExcuteWithReturn($"select file_id,file_path from {BIAOSHOPFILE} where file_id in('{string.Join("','", ids)}')").ToModels();

                                ret.Maplist_MapArgs.Add("Files", files);
                            }
                        }
                    }



                    ret.Map_Args = commodity;
                    ret.Byte_Flag = (sbyte)1;

                    mainsql.closesql();
                    tsall.Complete();
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 门店产品上架/下架
        [WebMethod(Description = "门店产品上架/下架")]
        [Obsolete]
        public string Shop_UpdateCommodityStatus(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_UpdateCommodityStatus) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var commodity_id = comrcv.Map_Args["commodityId"];//商品ID
                    var userId = comrcv.Map_Args["userId"];//当前登录用户
                    var status = comrcv.Map_Args["status"].ToInt32();//状态

                    int num = mainsql.SqlExcuteNoReturn($"update s_commodity set commodity_status={status},commodity_update_user='{userId}',commodity_update_time=NOW() where commodity_id='{commodity_id}'");

                    if (num > 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "操作成功";
                        ret.Byte_Flag = (sbyte)1;
                    }

                    mainsql.closesql();
                    tsall.Complete();
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 门店产品删除
        [WebMethod(Description = "门店产品删除")]
        [Obsolete]
        public string Shop_DelCommodityStatus(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_UpdateCommodityStatus) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var commodity_id = comrcv.Map_Args["commodityId"];//商品ID
                    var userId = comrcv.Map_Args["userId"];//当前登录用户

                    int num = mainsql.SqlExcuteNoReturn($"update s_commodity set commodity_isdel=1,commodity_update_user='{userId}',commodity_update_time=NOW() where commodity_id='{commodity_id}'");

                    if (num > 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "操作成功";
                        ret.Byte_Flag = (sbyte)1;
                    }

                    mainsql.closesql();
                    tsall.Complete();
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 生成商品订单
        [WebMethod(Description = "生成商品订单")]
        [Obsolete]
        public string Shop_AddCommodityOrder(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_UpdateCommodityStatus) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    string userId = comrcv.Map_Args["userId"];            //用户onlyId
                    string commodityId = comrcv.Map_Args["commodityId"]; //商品ID
                    string companyId = comrcv.Map_Args["companyId"]; //公司ID
                    string price = comrcv.Map_Args["actualPrice"]; //原金额
                    string payPrice = comrcv.Map_Args["payPrice"]; //优惠金额
                    string yhqId = comrcv.Map_Args["yhqId"]; //优惠券ID
                    string buyOrderId = Guid.NewGuid().ToString();

                    double priceD = 0;
                    double payPriceD = 0;
                    double.TryParse(price, out priceD);
                    double.TryParse(payPrice, out payPriceD);

                    //用户是否存在
                    var sqlc = $"select * from yonghualluser where user_onlyid='{userId}'";
                    var ds = mainsql.SqlExcuteWithReturn(sqlc);
                    if (ds.Rows.Count == 0)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "用户不存在";

                        goto EXIT;
                    };

                    var user_id = userId;
                    var user_name = ds.Rows[0]["user_name"].ToString();
                    var user_phone = ds.Rows[0]["user_phone"].ToString();


                    //修理厂是否存在
                    sqlc = $"select * from s_usercompany where user_id ='{companyId}'";

                    loginfo.Info(sqlc);
                    ds = mainsql.SqlExcuteWithReturn(sqlc);
                    if (ds.Rows.Count == 0)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "修理厂不存在";

                        goto EXIT;
                    };

                    var shopName = ds.Rows[0]["user_companyname"].ToString();

                    int payStatus = 0;

                    if (!string.IsNullOrWhiteSpace(yhqId))
                    {
                        //修改订单未支付订单状态 1：已使用
                        var sql = $"update s_coupon set coupon_status=1,coupon_updateime=NOW()  where Sid='{yhqId}';";

                        mainsql.SqlExcuteNoReturn(sql);

                        if (payPriceD == 0 || priceD == 0)
                        {
                            payStatus = 6;

                            string defaultstr = string.Format("用户使用优惠券，支付{0}元", payPriceD);

                            sql = string.Format("INSERT INTO {0} (zf_time,zf_type,zf_status,zf_qgnumber,zf_chnumber,zf_biaoid,zf_companyaccount," +
                                "zf_companynumber,zf_companyname,zf_yhamount,zf_yholdamount,zf_qgamount,zf_companyamount,zf_default,zf_zfphone,zf_way,zf_shouzhi,zf_comshouzhi,zf_zfonlyid)" +
                                " VALUES ('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','微信(优惠券)','2','1','{16}')",
                                BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "团购支付", "支付成功", "",
                                "", buyOrderId, companyId, "", shopName,
                                price, price, 0.ToString("0.00"), price, defaultstr, user_phone, user_id);

                            mainsql.SqlExcuteNoReturn(sql);
                        }
                    }

                    payPriceD = Math.Round(payPriceD, 2);
                    //生成订单
                    var sqlcmd = $@"INSERT INTO s_commoditybuyorder (buy_order_id,user_id,company_id,commodity_id,buy_order_status,buy_order_create_time,buy_order_pay_status,buy_order_price,buy_order_pay_price,buy_order_yhq)
                         VALUES ('{buyOrderId}','{userId}','{companyId}','{commodityId}','0','{DateTime.Now}','{payStatus}',{priceD},{payPriceD},'{yhqId}')";

                    loginfo.Info($"添加商品订单：{sqlcmd}");

                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret > 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "操作成功";
                        ret.Map_Args["orderId"] = buyOrderId;
                        ret.Byte_Flag = (sbyte)1;
                    }

                    mainsql.closesql();
                    tsall.Complete();
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 购物车商品订单
        [WebMethod(Description = "购物车商品订单")]
        [Obsolete]
        public string CouponPlaceOrder(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(CouponPlaceOrder) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (MySqlTransaction tr = mainsql.Connection().BeginTransaction())
                {
                    string orderDetails = comrcv.Map_Args["orderDetails"];
                    //string orderDetails = @"[{""userId"": """",   ""commodityId"": ""1234"",  ""couponId"": """",  ""actualPrice"": 0,  ""payPrice"": 0  },
                    //                         {""userId"": """",   ""commodityId"": ""1234"",  ""couponId"": ""32132131"", ""actualPrice"": 12, ""payPrice"": 32}
                    //                        ]";
                    var buyOrderIds = string.Empty;

                    if (string.IsNullOrWhiteSpace(orderDetails))
                    {
                        ret.Map_Args["ErrorMsg"] = "订单数据不能为空！";
                        goto EXIT;
                    }

                    JArray orderArr = JsonConvert.DeserializeObject<JArray>(orderDetails);

                    if (orderArr == null || orderArr.Count == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "订单数据错误！";
                        goto EXIT;
                    }

                    foreach (var item in orderArr)
                    {
                        string userId = item.Value<string>("userId");       //用户onlyId
                        string commodityId = item.Value<string>("commodityId");  //商品ID
                        string couponId = item.Value<string>("couponId");   //优惠券ID
                        string price = item.Value<string>("actualPrice"); //原金额
                        string payPrice = item.Value<string>("payPrice"); //优惠金额
                        double priceD = 0;                                  //原金额
                        double payPriceD = 0;                               //优惠金额
                        double.TryParse(price, out priceD);
                        double.TryParse(payPrice, out payPriceD);

                        //用户是否存在
                        var sqlc = $"select * from yonghualluser where user_onlyid='{userId}'";
                        var ds = mainsql.SqlExcuteWithReturn(sqlc);

                        if (ds.Rows.Count == 0)
                        {
                            mainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "用户不存在";
                            goto EXIT;
                        };

                        var user_id = userId;
                        var user_name = ds.Rows[0]["user_name"].ToString();
                        var user_phone = ds.Rows[0]["user_phone"].ToString();

                        sqlc = $@"select * from s_commodity where commodity_id='{commodityId}'  and commodity_isdel=0 and commodity_status=1";
                        var commodity = mainsql.SqlExcuteWithReturn(sqlc).ToModels().FirstOrDefault();

                        if (commodity == null)
                        {
                            ret.Map_Args["ErrorMsg"] = "产品可能已下架，请刷新后再试";  //参数错误
                            mainsql.closesql();
                            goto EXIT;
                        }

                        string companyId = commodity["company_id"]; //公司ID

                        //修理厂是否存在
                        sqlc = $"select * from s_usercompany where user_id ='{companyId}'";
                        loginfo.Info(sqlc);
                        ds = mainsql.SqlExcuteWithReturn(sqlc);

                        if (ds.Rows.Count == 0)
                        {
                            mainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "修理厂不存在";
                            goto EXIT;
                        };

                        var shopName = ds.Rows[0]["user_companyname"].ToString();
                        var payStatus = 0;
                        var buyOrderId = Guid.NewGuid().ToString();      //订单ID

                        buyOrderIds += $"{buyOrderId},";//返回的订单号

                        if (!string.IsNullOrWhiteSpace(couponId))
                        {
                            //修改订单未支付订单状态
                            sqlc = $"update s_coupon set coupon_status=1,coupon_updateime=NOW() where Sid='{couponId}';";

                            mainsql.SqlExcuteNoReturn(sqlc, tr);

                            if (payPriceD == 0 || priceD == 0)
                            {
                                payStatus = 6;

                                string defaultstr = string.Format("用户使用优惠券，支付{0}元", payPriceD);

                                sqlc = string.Format("INSERT INTO {0} (zf_time,zf_type,zf_status,zf_qgnumber,zf_chnumber,zf_biaoid,zf_companyaccount," +
                                    "zf_companynumber,zf_companyname,zf_yhamount,zf_yholdamount,zf_qgamount,zf_companyamount,zf_default,zf_zfphone,zf_way,zf_shouzhi,zf_comshouzhi,zf_zfonlyid)" +
                                    " VALUES ('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','微信(优惠券)','2','1','{16}')",
                                    BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "团购支付", "支付成功", "",
                                    "", buyOrderId, companyId, "", shopName,
                                    price, price, 0.ToString("0.00"), price, defaultstr, user_phone, user_id);

                                mainsql.SqlExcuteNoReturn(sqlc, tr);
                            }
                        }

                        priceD = Math.Round(priceD, 2);
                        payPriceD = Math.Round(payPriceD, 2);

                        //生成订单
                        sqlc = $@"INSERT INTO s_commoditybuyorder (buy_order_id,user_id,company_id,commodity_id,buy_order_status,buy_order_create_time,buy_order_pay_status,buy_order_price,buy_order_pay_price,buy_order_yhq)
                                 VALUES ('{buyOrderId}','{userId}','{companyId}','{commodityId}','0','{DateTime.Now}','{payStatus}',{priceD},{payPriceD},'{couponId}')";

                        loginfo.Info($"添加商品订单：{sqlc}");

                        mainsql.SqlExcuteNoReturn(sqlc, tr);

                    }

                    tr.Commit();
                    ret.Map_Args["orderId"] = buyOrderIds;
                    ret.Byte_Flag = 1;
                }
            }
            catch (Exception ex)
            {
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            mainsql.closesql();
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 获取门店商品订单列表 前台
        [WebMethod(Description = "获取门店商品订单列表")]
        public string Shop_GetCommodityBuyOrderAll(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetCommodityBuyOrderAll) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                var userId = comrcv.Map_Args["userId"];//创建人ID

                var sql = $@"select d.user_name,d.user_phone,c.user_companyname,b.commodity_name,b.commodity_file_id, a.* from s_commoditybuyorder a 
                        left join s_commodity b on a.commodity_id=b.commodity_id
                        left join s_usercompany c on a.company_id=c.user_id
                        left join yonghualluser d on a.user_id=d.user_onlyid where a.user_id='{userId}' order by buy_order_create_time desc";

                var commpditytypes = mainsql.SqlExcuteWithReturn(sql).ToModels();

                commpditytypes.ForEach(t =>
                {
                    //编辑状态
                    if ((t["buy_order_pay_status"].Equals("1") || t["buy_order_pay_status"].Equals("6")) && t["buy_order_status"].Equals("0"))
                    {
                        t["orderStatus"] = "未核销";
                    }
                    else if ((t["buy_order_pay_status"].Equals("1") || t["buy_order_pay_status"].Equals("6")) && t["buy_order_status"].Equals("1"))
                    {
                        t["orderStatus"] = "已核销";
                    }
                    else if (t["buy_order_status"].Equals("2"))
                    {
                        t["orderStatus"] = "订单已取消";
                    }
                    else if (t["buy_order_pay_status"].Equals("2"))
                    {
                        t["orderStatus"] = "申请退款";
                    }
                    else if (t["buy_order_pay_status"].Equals("3"))
                    {
                        t["orderStatus"] = "等待退款";
                    }
                    else if (t["buy_order_pay_status"].Equals("4"))
                    {
                        t["orderStatus"] = "已退款";
                    }
                    else if (t["buy_order_pay_status"].Equals("5"))
                    {
                        t["orderStatus"] = "支付失败";
                    }
                    else
                    {
                        t["orderStatus"] = "未支付";
                    }

                    //获取图片
                    t["file_small_path"] = "";

                    if (!string.IsNullOrWhiteSpace(t["commodity_file_id"]))
                    {
                        var ids = t["commodity_file_id"].Split(',');

                        if (ids.Length > 0)
                        {
                            t["file_small_path"] = mainsql.SqlExecuteScalar($"select file_path from s_files where file_id='{ids[0]}' limit 0,1").ToString();
                        }
                    }
                });

                ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
                ret.Maplist_MapArgs.Add("Data", commpditytypes);
                ret.Map_Args["ErrorMsg"] = "操作成功";
                ret.Byte_Flag = (sbyte)1;

                mainsql.closesql();
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        #endregion

        #region 获取门店商品订单列表 后台
        [WebMethod(Description = "获取门店商品订单列表")]
        public string Shop_GetBackstageOrderAll(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetCommodityBuyOrderAll) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                var companyId = comrcv.Map_Args["companyId"];//创建人ID

                var sql = $@"select d.user_name,d.user_phone,c.user_companyname,b.commodity_name,b.commodity_file_id, a.* from s_commoditybuyorder a 
                        left join s_commodity b on a.commodity_id=b.commodity_id
                        left join s_usercompany c on a.company_id=c.user_id
                        left join yonghualluser d on a.user_id=d.user_onlyid where  buy_order_pay_status <> 0 and buy_order_pay_status <> 5 and buy_order_status <> 2 and a.company_id='{companyId}' order by buy_order_create_time desc";

                var commpditytypes = mainsql.SqlExcuteWithReturn(sql).ToModels();

                commpditytypes.ForEach(t =>
                {
                    //编辑状态
                    if ((t["buy_order_pay_status"].Equals("1") || t["buy_order_pay_status"].Equals("6")) && t["buy_order_status"].Equals("0"))
                    {
                        t["orderStatus"] = "未核销";
                    }
                    else if ((t["buy_order_pay_status"].Equals("1") || t["buy_order_pay_status"].Equals("6")) && t["buy_order_status"].Equals("1"))
                    {
                        t["orderStatus"] = "已核销";
                    }
                    else if (t["buy_order_status"].Equals("2"))
                    {
                        t["orderStatus"] = "订单已取消";
                    }
                    else if (t["buy_order_pay_status"].Equals("2"))
                    {
                        t["orderStatus"] = "申请退款";
                    }
                    else if (t["buy_order_pay_status"].Equals("3"))
                    {
                        t["orderStatus"] = "等待退款";
                    }
                    else if (t["buy_order_pay_status"].Equals("4"))
                    {
                        t["orderStatus"] = "已退款";
                    }
                    else if (t["buy_order_pay_status"].Equals("5"))
                    {
                        t["orderStatus"] = "支付失败";
                    }
                    else
                    {
                        t["orderStatus"] = "未支付";
                    }

                    //获取图片
                    t["file_small_path"] = "";

                    if (!string.IsNullOrWhiteSpace(t["commodity_file_id"]))
                    {
                        var ids = t["commodity_file_id"].Split(',');

                        if (ids.Length > 0)
                        {
                            t["file_small_path"] = mainsql.SqlExecuteScalar($"select file_path from s_files where file_id='{ids[0]}' limit 0,1").ToString();
                        }
                    }
                });

                ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
                ret.Maplist_MapArgs.Add("Data", commpditytypes);
                ret.Map_Args["ErrorMsg"] = "操作成功";
                ret.Byte_Flag = (sbyte)1;

                mainsql.closesql();
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        #endregion

        #region 核销订单
        [WebMethod(Description = "核销订单")]
        public string Shop_UpdateBuyOrderStatus(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_UpdateBuyOrderStatus) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (var tr = mainsql.Connection().BeginTransaction())
                {
                    var buy_order_id = comrcv.Map_Args["buyOrderId"];//商品订单ID
                    var userId = comrcv.Map_Args["userId"];//当前登录用户
                    var status = comrcv.Map_Args["status"];//0：未核销，1：核销，2：订单取消

                    var sql = $@"select * from s_commoditybuyorder where buy_order_status=0 and (buy_order_pay_status=1||buy_order_pay_status=6) and buy_order_id='{buy_order_id}'";
                    var order = mainsql.SqlExcuteWithReturn(sql).ToModels().FirstOrDefault();
                    if (order == null)
                    {
                        ret.Map_Args["ErrorMsg"] = "未找到订单";  //参数错误
                        goto EXIT;
                    }

                    var companyId = order["company_id"].ToString();
                    var price = order["buy_order_price"].ToString();//订单金额
                    var payPrice = order["buy_order_pay_price"].ToString();//订单金额
                    var coponId = order["buy_order_yhq"].ToString();//订单使用的优惠券
                    double payPriceD = 0;
                    double.TryParse(payPrice, out payPriceD);

                    //用户是否存在
                    sql = $"select * from yonghualluser where user_onlyid='{userId}'";
                    var user = mainsql.SqlExcuteWithReturn(sql).ToModels().FirstOrDefault();
                    if (user == null)
                    {
                        ret.Map_Args["ErrorMsg"] = "用户不存在";

                        goto EXIT;
                    };

                    var user_id = userId;
                    var user_name = user["user_name"].ToString();
                    var user_phone = user["user_phone"].ToString();

                    //修理厂是否存在
                    sql = $"select * from s_usercompany where user_id ='{companyId}'";
                    var company = mainsql.SqlExcuteWithReturn(sql).ToModels().FirstOrDefault();

                    if (company == null)
                    {
                        ret.Map_Args["ErrorMsg"] = $"修理厂不存在，公司ID:{companyId}";

                        goto EXIT;
                    };

                    var shopName = company["user_companyname"].ToString();
                    var salerate = company["user_salerate"].ToString();//公司费率
                    decimal priceDec = 0;
                    decimal salerateDec = 0;
                    decimal.TryParse(price, out priceDec);
                    decimal.TryParse(salerate, out salerateDec);

                    //查找优惠券
                    decimal companyPrice = 0;
                    var remark = string.Empty;

                    if (!string.IsNullOrWhiteSpace(coponId))
                    {
                        sql = $"select * from s_coupon where Sid ='{coponId}'";
                        var copon = mainsql.SqlExcuteWithReturn(sql).ToModels().FirstOrDefault();

                        if (copon != null)
                        {
                            //充值类型  0：预充值（平台发放）1：免充值（商家发放）
                            switch (copon["coupon_recharge_type"])
                            {
                                case "0":
                                    remark = "用户使用优惠券（预充值），";
                                    companyPrice = priceDec * salerateDec;
                                    break;

                                case "1":

                                    remark = "用户使用优惠券（免充值），";
                                    //优惠券面值
                                    decimal couponAmount = 0;

                                    //0：满减券，1：代金券，2：换购券
                                    switch (copon["coupon_type"])
                                    {
                                        case "0":
                                        case "1":
                                            decimal.TryParse(copon["coupon_amount"], out couponAmount);
                                            break;

                                        default:
                                            couponAmount = priceDec;
                                            break;
                                    }

                                    priceDec = priceDec - couponAmount;
                                    break;
                            }
                        };
                    }


                    companyPrice = priceDec * salerateDec;

                    //修改订单未支付订单状态
                    sql = $@"update s_commoditybuyorder set buy_order_status={status},buy_order_update_time=NOW() where buy_order_id='{buy_order_id}'";
                    mainsql.SqlExcuteNoReturn(sql, tr);

                    //修改到账金额
                    sql = $"update s_usercompany set user_price=user_price + ({companyPrice}) where user_id='{companyId}'";
                    mainsql.SqlExcuteNoReturn(sql);

                    //加入流水
                    string defaultstr = $"用户核销,{remark}公司实际到账{Math.Round((priceDec * salerateDec), 2)}元";
                    sql = string.Format("INSERT INTO {0} (zf_time,zf_type,zf_status,zf_qgnumber,zf_chnumber,zf_biaoid,zf_companyaccount," +
                        "zf_companynumber,zf_companyname,zf_yhamount,zf_yholdamount,zf_qgamount,zf_companyamount,zf_default,zf_zfphone,zf_way,zf_shouzhi,zf_comshouzhi,zf_zfonlyid)" +
                        " VALUES ('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','微信','2','1','{16}')",
                        BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "团购支付", "核销成功", "",
                        "", buy_order_id, companyId, "", shopName,
                        price, price, 0.ToString("0.00"), Math.Round((priceDec * salerateDec), 2), defaultstr, user_phone, user_id);

                    mainsql.SqlExcuteNoReturn(sql, tr);

                    tr.Commit();
                    ret.Byte_Flag = 1;
                }
            }
            catch (Exception ex)
            {
                ret.Map_Args["ErrorMsg"] = $"核销失败：{ex.Message}";  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            mainsql.closesql();
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 取消订单
        [WebMethod(Description = "取消订单")]
        public string Shop_CancelCommodityBuyOrder(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_CancelCommodityBuyOrder) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var buy_order_id = comrcv.Map_Args["buyOrderId"];//商品订单ID
                    var userId = comrcv.Map_Args["userId"];//当前登录用户
                    var status = comrcv.Map_Args["status"];//0：未核销，1：核销，2：订单取消

                    var paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@buy_order_id", buy_order_id));
                    paras.Add(new MySqlParameter("@userId", userId));
                    paras.Add(new MySqlParameter("@status", status));

                    var sql = $@"select * from s_commoditybuyorder where buy_order_id='{buy_order_id}' ";
                    var ds = mainsql.SqlExcuteWithReturn(sql);
                    if (ds.Rows.Count == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "未找到订单";  //参数错误
                        mainsql.closesql();
                        goto EXIT;
                    }

                    sql = $@"update s_commoditybuyorder set buy_order_status=@status,buy_order_update_time=NOW() where buy_order_id=@buy_order_id and user_id=@userId";
                    var num = mainsql.SqlExcuteNoReturn(sql, paras.ToArray());

                    if (num > 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "操作成功";  //参数错误
                        ret.Byte_Flag = (sbyte)1;
                    }

                    mainsql.closesql();
                    tsall.Complete();

                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 申请退款
        [WebMethod(Description = "申请退款")]
        public string Shop_ApplyForRefund(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_ApplyForRefund) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var buy_order_id = comrcv.Map_Args["buyOrderId"];//商品订单ID

                    var paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@orderId", buy_order_id));

                    var sql = $@"select * from s_commoditybuyorder where buy_order_pay_status=1 and buy_order_status=0  and buy_order_id='{buy_order_id}'";
                    var ds = mainsql.SqlExcuteWithReturn(sql);
                    if (ds.Rows.Count == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "订单已核销，无法退款";  //参数错误
                        mainsql.closesql();
                        goto EXIT;
                    }

                    sql = "update s_commoditybuyorder set buy_order_pay_status=2,buy_order_update_time=NOW() where buy_order_id=@orderId;";
                    loginfo.Info(sql);
                    var num = mainsql.SqlExcuteNoReturn(sql, paras.ToArray());
                    if (num < 1)
                    {
                        ret.Map_Args["ErrorMsg"] = "申请退款失败";
                        loginfo.Info("申请退款失败：" + sql);
                        goto EXIT;
                    }

                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                    ret.Map_Args["ErrorMsg"] = "操作成功";  //参数错误

                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            mainsql.closesql();
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 获取用户列表

        [WebMethod(Description = "获取用户列表")]
        public string Shop_GetUserAll(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetUserAll) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {

                var page = 1;//创建人ID
                var limit = 10;//创建人ID
                var pagep = comrcv.Map_Args["page"];//
                var limitp = comrcv.Map_Args["limit"];//
                var name = string.Empty;
                var phone = string.Empty;
                var time = string.Empty;

                int.TryParse(pagep, out page);
                int.TryParse(limitp, out limit);
                page = page <= 0 ? 1 : page;
                limit = limit <= 0 ? 50 : limit;

                StringBuilder sqlWhere = new StringBuilder(" where 1=1");

                if (comrcv.Map_Args.Keys.Contains("name"))
                {
                    name = comrcv.Map_Args["name"];
                }
                if (comrcv.Map_Args.Keys.Contains("phone"))
                {
                    phone = comrcv.Map_Args["phone"];
                }
                if (comrcv.Map_Args.Keys.Contains("time"))
                {
                    time = comrcv.Map_Args["time"];
                }

                if (!string.IsNullOrWhiteSpace(name))
                {
                    sqlWhere.AppendFormat(" and a.user_name like '%{0}%'", name);
                }

                if (!string.IsNullOrWhiteSpace(phone))
                {
                    sqlWhere.AppendFormat(" and a.user_phone like '%{0}%'", phone);
                }

                string timeSql = " where 1=1";
                if (!string.IsNullOrWhiteSpace(time))
                {
                    var startTime = time.Split('~')[0];
                    var endTime = DateTime.Parse(time.Split('~')[1]);
                    timeSql += $" and order_create_time>='{startTime}' && order_create_time<'{endTime.AddDays(1)}'";
                }

                sqlWhere.AppendFormat(" order by b.usercount desc");

                var sql = $"select count(1) from yonghualluser a left JOIN ( select order_create_user,COUNT(order_create_user) as usercount from  s_order {timeSql} GROUP BY order_create_user) b on a.user_onlyid=b.order_create_user {sqlWhere}";
                var count = mainsql.SqlExecuteScalar(sql).ToInt32();

                sql = $"select  b.usercount,a.* from yonghualluser a left JOIN ( select order_create_user,COUNT(order_create_user) as usercount from  s_order {timeSql} GROUP BY order_create_user) b on a.user_onlyid=b.order_create_user  {sqlWhere}  limit {limit * page - limit},{limit}";
                var result = mainsql.SqlExcuteWithReturn(sql).ToModels();

                ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
                ret.Maplist_MapArgs.Add("Data", result);
                ret.Map_Args["Count"] = count.ToString();
                ret.Map_Args["ErrorMsg"] = "操作成功";
                ret.Byte_Flag = (sbyte)1;

                mainsql.closesql();
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 团购产品加入购物车
        [WebMethod(Description = "加入购物车")]
        public string AddToCart(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(AddToCart) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                var commodityId = comrcv.Map_Args["commodityId"];//商品ID
                var userId = comrcv.Map_Args["userId"];//当前登录用户
                //var commodityId = "1699fbfa-465a-46c4-8cbd-021c2324f57e";
                //var userId = "40d2f446-8c99-4614-8d13-4980eae56f58";

                //购物车中是否存在该商品
                var sql = $"select * from {BIAOBUYERCOLLPRODUCT} where prd_id='{commodityId}' and user_id='{userId}'";
                var ds = mainsql.SqlExcuteWithReturn(sql);

                if (ds.Rows.Count > 0)
                {
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "产品已在购物车啦~";
                    goto EXIT;
                };

                //用户是否存在
                sql = $"select * from yonghualluser where user_onlyid='{userId}'";
                ds = mainsql.SqlExcuteWithReturn(sql);

                if (ds.Rows.Count == 0)
                {
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "用户不存在";
                    goto EXIT;
                };

                sql = $@"select * from s_commodity where commodity_id='{commodityId}'  and commodity_isdel=0 and commodity_status=1";
                ds = mainsql.SqlExcuteWithReturn(sql);

                if (ds.Rows.Count == 0)
                {
                    ret.Map_Args["ErrorMsg"] = "产品可能已下架，请刷新后再试";  //参数错误
                    mainsql.closesql();
                    goto EXIT;
                }

                sql = $@"insert into {BIAOBUYERCOLLPRODUCT} 
                        (user_id,prd_id,prd_coll_index,prd_coll_number,prd_coll_create_time,prd_coll_create_user,prd_coll_deleteflag,prd_source) values 
                        ('{userId}','{commodityId}','1','1', now(),'{userId}','0',1); ";

                mainsql.SqlExcuteNoReturn(sql);

                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex.Message);
            }

        EXIT:

            mainsql.closesql();
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        #endregion

        #endregion

        #region 订单

        private const string BIAOORDER = "s_order";
        private const string BIAOORDERPRODUCT = "s_orderproduct";
        private const string BIAOORDERADD = "s_orderadd";
        private const string BIAOCOMPANY = "s_company";
        private const string BIAOCOMPANYR = "s_companyrecord";
        private const string BIAOORDERSALE = "s_ordersale";
        private const string BIAOORDERSALEADD = "s_ordersaleadd";
        private const string BIAOORDERFENCHENG = "s_fenchengorder";


        #region 下单
        [WebMethod(Description = "下单")]
        public string Shop_AddOrder(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_AddOrder) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"]; //创建人ID
                    var ordertype = 0;//0：正常订单；1：卖家下单；2：买家下单
                    var daifu = 1; //0支持代付，1不支持
                    var shops = new List<Dictionary<string, object>>();
                    var fileids = new List<string>();
                    /**
                     * 买家选择产品、产品数量，选择收货地址，填写备注，下单
                     * 买家付款：任何人都可以付款
                     * 卖家发货，填写物流单号、物流名称、分包（不能一次打包，需要多个物流运送）
                     * 买家确认收货。
                     * 买家评价
                     * */
                    /**
                     * 卖家生成订单，填写产品名、产品价格、运费、备注、选择买家、选择买家收货地址
                     * 买家付款：任何人都可以付款
                     * */
                    double sumPrice = 0;
                    double sumfreigth = 0;

                    #region 产品数据，产品、购物车
                    if (comrcv.Map_Args.ContainsKey("Shops"))
                    {
                        var jsonStr = comrcv.Map_Args["Shops"];
                        if (!string.IsNullOrWhiteSpace(jsonStr))
                        {
                            JArray json = JsonConvert.DeserializeObject<JArray>(jsonStr);

                            if (json != null && json.Count > 0)
                            {
                                foreach (var item in json)
                                {
                                    //产品ID、SKU、数量、单位、单价、运费、店铺ID
                                    var model = new Dictionary<string, object>();
                                    var pJson = item.Value<JArray>("Products");
                                    var ps = new List<Dictionary<string, object>>();
                                    foreach (var pItem in pJson)
                                    {
                                        var product = new Dictionary<string, object>();
                                        var price = pItem.Value<string>("Price").ToDouble();
                                        var number = pItem.Value<string>("Number").ToInt32();
                                        var freight = pItem.Value<string>("Freight").ToDouble();
                                        product.Add("ProductId", pItem.Value<string>("ProductId").ToLong()); //id 可空
                                        product.Add("Name", pItem.Value<string>("Name"));                    //名称 如果有id就可空
                                        product.Add("Sku", pItem.Value<string>("Sku") ?? string.Empty);      //sku，用户选择的产品配置 可空
                                        product.Add("Number", number);      //产品数量 必须
                                        product.Add("Unit", pItem.Value<string>("Unit"));                    //数量单位 可空
                                        product.Add("ShortDescript", pItem.Value<string>("ShortDescript"));                    //数量单位 可空
                                        product.Add("Price", price);       //产品单价 如果有id就可空
                                        product.Add("Freight", freight);   //当前产品总运费计算后的价格，0包邮 必须
                                        var fileid = pItem.Value<string>("Files");
                                        product.Add("CoverFile", fileid);
                                        if (!string.IsNullOrWhiteSpace(fileid))
                                            fileids.AddRange(fileid.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries));
                                        sumPrice += (price * number);
                                        sumfreigth += freight;
                                        ps.Add(product);
                                    }
                                    model.Add("ShopId", item.Value<string>("ShopId"));                //店铺ID 必须
                                    model.Add("Content", item.Value<string>("Content"));                //备注 可空
                                    model.Add("Products", ps);
                                    shops.Add(model);
                                }
                            }
                        }
                    }
                    #endregion

                    if (shops.Count == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "参数错误，产品必须有";
                        mainsql.closesql();
                        goto EXIT;
                    }

                    if (shops.Count > 1)
                    {
                        ret.Map_Args["ErrorMsg"] = "参数错误，不能选择多个店铺下单";
                        mainsql.closesql();
                        goto EXIT;
                    }

                    #region 删除购物车数据,购物车
                    if (comrcv.Map_Args.ContainsKey("collids"))
                    {
                        var ids = comrcv.Map_Args["collids"]?.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                        if (ids.Length > 0)
                            mainsql.SqlExcuteNoReturn($"delete from {BIAOBUYERCOLLPRODUCT} where prd_coll_id in({string.Join(",", ids)})");
                    }
                    #endregion

                    #region 收货信息
                    var toUserId = comrcv.Map_Args["ToUserId"]; //收货人ID,必传
                    var toAddress = comrcv.Map_Args.ContainsKey("ToAddress") ? comrcv.Map_Args["ToAddress"] : string.Empty; //收货地址
                    var toPhone = comrcv.Map_Args.ContainsKey("ToPhone") ? comrcv.Map_Args["ToPhone"] : string.Empty; //收货电话
                    var toUser = comrcv.Map_Args.ContainsKey("ToUser") ? comrcv.Map_Args["ToUser"] : string.Empty; //收货人名
                    #endregion

                    var ordernumber = DateTime.Now.Ticks.ToString();
                    long order = 0;

                    #region //添加主单信息
                    //if (shops.Count > 1)
                    //{
                    //    StringBuilder sql = new StringBuilder();
                    //    sql.AppendFormat("insert into {0}(order_type,order_number,order_price,order_daifu,order_freight,order_to_address,order_to_phone,order_to_user,order_to_user_id,order_pay_method,order_status,order_create_time,order_create_user,order_deleteflag)"
                    //        + "values(@Type,@ordernumber,@Price,@order_daifu,@Freight,@ToAddress,@ToPhone,@ToUser,@ToUserId,0,@status,NOW(),@userid,0);SELECT @@IDENTITY", BIAOORDER);
                    //    var paras = new List<MySqlParameter>();
                    //    paras.Add(new MySqlParameter("@Type", ordertype));
                    //    paras.Add(new MySqlParameter("@Price", sumPrice));
                    //    paras.Add(new MySqlParameter("@order_daifu", daifu));
                    //    paras.Add(new MySqlParameter("@Freight", sumfreigth));
                    //    paras.Add(new MySqlParameter("@ToAddress", toAddress));
                    //    paras.Add(new MySqlParameter("@ToPhone", toPhone));
                    //    paras.Add(new MySqlParameter("@ToUser", toUser));
                    //    paras.Add(new MySqlParameter("@ToUserId", toUserId));
                    //    paras.Add(new MySqlParameter("@userid", userid));
                    //    paras.Add(new MySqlParameter("@ordernumber", ordernumber));
                    //    if (ordertype == 2)
                    //    {
                    //        paras.Add(new MySqlParameter("@status", 6));
                    //    }
                    //    else
                    //    {
                    //        paras.Add(new MySqlParameter("@status", 0));
                    //    }
                    //    order = mainsql.SqlExecuteScalar(sql.ToString(), paras.ToArray()).ToLong();
                    //    if (order <= 0)
                    //    {
                    //        ret.Map_Args["ErrorMsg"] = "系统错误，添加失败";
                    //        mainsql.closesql();
                    //        goto EXIT;
                    //    }
                    //}
                    #endregion


                    #region 添加子单信息
                    foreach (var item in shops)
                    {
                        var shopId = item["ShopId"]?.ToString();
                        var descript = item["Content"]?.ToString() ?? string.Empty;
                        if (string.IsNullOrWhiteSpace(shopId))
                        {
                            ret.Map_Args["ErrorMsg"] = "参数错误，店铺ID不能为空";
                            mainsql.closesql();
                            goto EXIT;
                        }
                        var shopModel = mainsql.SqlExcuteWithReturn($"select * from {BIAOSHOP} where shop_id='{shopId}'").ToModels().FirstOrDefault();
                        if (shopModel == null || !shopModel.ContainsKey("shop_status"))
                        {
                            ret.Map_Args["ErrorMsg"] = "数据错误，不存在的店铺";
                            mainsql.closesql();
                            goto EXIT;
                        }
                        if (shopModel["shop_status"].ToInt32() != 0)
                        {
                            ret.Map_Args["ErrorMsg"] = "店铺未开启，不允许下单";
                            mainsql.closesql();
                            goto EXIT;
                        }
                        var products = item["Products"] as List<Dictionary<string, object>>;
                        if (products.Count == 0)
                        {
                            ret.Map_Args["ErrorMsg"] = "参数错误，产品信息不存在";
                            mainsql.closesql();
                            goto EXIT;
                        }
                        if (order > 0)
                        {
                            sumPrice = products.Sum(x => x["Price"].ToDouble() * x["Number"].ToInt32());
                            sumfreigth = products.Sum(x => x["Freight"].ToDouble());
                        }

                        StringBuilder sql = new StringBuilder();
                        if (daifu == 0)
                        {
                            sql.AppendFormat("insert into {0}(order_parent_id,order_number,shop_id,order_type,order_price,order_daifu,order_freight,order_to_address,order_to_phone,order_to_user,order_to_user_id,order_pay_method,order_status,order_create_time,order_create_user,order_deleteflag,order_pay_time)"
                                + "values(@OrderId,@ordernumber,@ShopId,@Type,@Price,@order_daifu,@Freight,@ToAddress,@ToPhone,@ToUser,@ToUserId,1,@status,NOW(),@userid,0,NOW());SELECT @@IDENTITY", BIAOORDER);
                        }
                        else
                        {
                            sql.AppendFormat("insert into {0}(order_parent_id,order_number,shop_id,order_type,order_price,order_daifu,order_freight,order_to_address,order_to_phone,order_to_user,order_to_user_id,order_pay_method,order_status,order_create_time,order_create_user,order_deleteflag)"
                                + "values(@OrderId,@ordernumber,@ShopId,@Type,@Price,@order_daifu,@Freight,@ToAddress,@ToPhone,@ToUser,@ToUserId,0,@status,NOW(),@userid,0);SELECT @@IDENTITY", BIAOORDER);
                        }
                        var paras = new List<MySqlParameter>();
                        paras.Add(new MySqlParameter("@ShopId", shopId));
                        paras.Add(new MySqlParameter("@Type", ordertype));
                        paras.Add(new MySqlParameter("@Price", sumPrice));
                        paras.Add(new MySqlParameter("@order_daifu", daifu));
                        paras.Add(new MySqlParameter("@Freight", sumfreigth));
                        paras.Add(new MySqlParameter("@ToAddress", toAddress));
                        paras.Add(new MySqlParameter("@ToPhone", toPhone));
                        paras.Add(new MySqlParameter("@ToUser", toUser));
                        paras.Add(new MySqlParameter("@ToUserId", toUserId));
                        paras.Add(new MySqlParameter("@userid", userid));
                        paras.Add(new MySqlParameter("@ordernumber", ordernumber));
                        if (order > 0)
                        {
                            paras.Add(new MySqlParameter("@OrderId", order));
                        }
                        else
                        {
                            paras.Add(new MySqlParameter("@OrderId", MySqlDbType.Int64) { Value = DBNull.Value });
                        }
                        if (ordertype == 2)
                        {
                            paras.Add(new MySqlParameter("@status", 6));
                        }
                        else
                        {
                            if (daifu == 0)
                            {
                                //货到付款 直接待发货
                                paras.Add(new MySqlParameter("@status", MySqlDbType.Int32) { Value = 1 });
                            }
                            else
                            {
                                paras.Add(new MySqlParameter("@status", MySqlDbType.Int32) { Value = 0 });
                            }
                        }

                        //创建订单 addorder
                        var orderId = mainsql.SqlExecuteScalar(sql.ToString(), paras.ToArray()).ToLong();
                        if (order == 0) order = orderId;
                        if (!string.IsNullOrWhiteSpace(descript))
                        {//添加订单备注
                            var paras3 = new List<MySqlParameter>();
                            paras3.Add(new MySqlParameter("@OrderId", orderId));
                            paras3.Add(new MySqlParameter("@Content", descript));
                            paras3.Add(new MySqlParameter("@userid", userid));
                            mainsql.SqlExcuteNoReturn($"insert into {BIAOORDERADD}(order_id,order_add_create_time,order_add_create_user,order_add_type,order_add_parent_id,order_add_content)values(@OrderId,NOW(),@userid,0,null,@Content)", paras3.ToArray());
                        }

                        foreach (var pItem in products)
                        {
                            //添加订单产品 addproduct
                            var produtId = pItem["ProductId"].ToLong();
                            if (produtId > 0)
                            {
                                //卖家店铺产品
                                string addSQL = $"insert into {BIAOORDERPRODUCT}(order_prd_cover_id,order_id,prd_id,order_prd_type_id,order_prd_sku,order_prd_number,order_prd_name,order_prd_short_descript,order_prd_descript,order_prd_logo_ids,order_prd_price,order_prd_unit,order_prd_create_time,order_prd_create_user,order_prd_freight) "
                                + $"select prd_cover_id,{orderId},prd_id,prd_type_id,'{pItem["Sku"]}',{pItem["Number"].ToInt32()},prd_name,prd_short_descript,prd_descript,prd_logo_ids,prd_price,prd_unit,NOW(),'{userid}',{pItem["Freight"].ToDouble()} from {BIAOPRODUCT} where prd_id={produtId} and shop_id='{shopId}'";
                                if (mainsql.SqlExcuteNoReturn(addSQL) != 1)
                                {
                                    ret.Map_Args["ErrorMsg"] = "参数错误，店铺ID和产品ID不一致";
                                    mainsql.closesql();
                                    goto EXIT;
                                }
                                //店铺产品库存扣除
                                //if (mainsql.SqlExecuteScalar($"update {BIAOPRODUCT} set prd_stock_number=prd_stock_number-{pItem["Number"].ToInt32()} where prd_id={produtId};select prd_stock_number from {BIAOPRODUCT} where prd_id={produtId}").ToInt32() < 0)
                                //{
                                //    ret.Map_Args["ErrorMsg"] = "产品库存不足";
                                //    mainsql.closesql();
                                //    goto EXIT;
                                //}
                            }
                            else
                            {
                                //卖家自定义产品
                                string addSQL = $"insert into {BIAOORDERPRODUCT}(order_id,order_prd_number,order_prd_name,order_prd_price,order_prd_unit,order_prd_create_time,order_prd_create_user,order_prd_freight,order_prd_sku,order_prd_cover_id,order_prd_short_descript,order_prd_logo_ids) "
                                    + "values(@OrderId,@ProductNumber,@Name,@Price,@Unit,NOW(),@UserId,@Freight,@Sku,@CoverFile,@ShortDescript,@fileids)";
                                var files = pItem["CoverFile"]?.ToString()?.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);

                                var paras2 = new List<MySqlParameter>();
                                paras2.Add(new MySqlParameter("@OrderId", orderId));
                                paras2.Add(new MySqlParameter("@Sku", pItem["Sku"]));
                                paras2.Add(new MySqlParameter("@ProductNumber", pItem["Number"].ToInt32()));
                                paras2.Add(new MySqlParameter("@Name", pItem["Name"]));
                                paras2.Add(new MySqlParameter("@Unit", pItem["Unit"]));
                                paras2.Add(new MySqlParameter("@CoverFile", files.Length == 0 ? "" : files.FirstOrDefault()));
                                paras2.Add(new MySqlParameter("@fileids", pItem["CoverFile"]));
                                paras2.Add(new MySqlParameter("@ShortDescript", pItem["ShortDescript"]));
                                paras2.Add(new MySqlParameter("@Price", pItem["Price"].ToDouble()));
                                paras2.Add(new MySqlParameter("@Freight", pItem["Freight"].ToDouble()));
                                paras2.Add(new MySqlParameter("@UserId", userid));
                                mainsql.SqlExcuteNoReturn(addSQL, paras2.ToArray());
                            }
                        }

                        if (ordertype == 2) //买家下单
                        {
                            ILog logJieKou = LogManager.GetLogger("LoggerJieKou");
                            var phone = shopModel["shop_tel_number"];
                            var shopName = shopModel["shop_name"];
                            //if (!string.IsNullOrWhiteSpace(phone))
                            //{
                            //    var i = SmsSendInterface.sendOnce(phone, "尊敬的（" + shopName + "）商户您好，您的店铺有一条新的询价订单，请尽快进入青贯助手小程序查看。");

                            //    logJieKou.Info($"发送消息短信：{phone} 返回结果：{i}");
                            //}
                            //else
                            //{
                            //    logJieKou.Info($"发送消息短信：没有号码");
                            //}
                            {
                                #region 发微信消息
                                var users = mainsql.SqlExcuteWithReturn($"select t2.user_openid_juhesheng,t2.user_phone,t2.user_name from {BIAOSHOPUSER} t1 left join {BIAOUSER} t2 on t1.user_id=t2.user_onlyid where shop_id='{shopId}' and shop_user_ismsg=1 and shop_user_deleteflag<>1").ToModels();
                                foreach (var uitem in users)
                                {
                                    var openid = uitem["user_openid_juhesheng"];
                                    if (!string.IsNullOrWhiteSpace(openid))
                                    {
                                        //发送消息
                                        WebServiceShopping.wechartTools.SendMsg(new WebServiceShopping.wechartTools.OrderMsg()
                                        {
                                            miniprogram = new WebServiceShopping.wechartTools.XCXPath()
                                            {
                                                pagepath = "/pages/my/store/store?ShopId=" + shopId
                                            },
                                            touser = openid,
                                            data = new WebServiceShopping.wechartTools.OrderMsg.DataModel()
                                            {
                                                first = new WebServiceShopping.wechartTools.DataItem()
                                                {
                                                    value = "您有新的询价订单"
                                                },
                                                keyword2 = new WebServiceShopping.wechartTools.DataItem()
                                                {
                                                    value = ordernumber
                                                },
                                                keyword3 = new WebServiceShopping.wechartTools.DataItem()
                                                {
                                                    value = DateTime.Now.ToString("yyyy年MM月dd HH:mm")
                                                },
                                                keyword1 = new WebServiceShopping.wechartTools.DataItem()
                                                {
                                                    value = "询价单"
                                                }
                                            }
                                        });
                                    }
                                }
                                #endregion
                            }
                        }
                        else if (ordertype == 1) //卖家下单
                        {
                            ILog logJieKou = LogManager.GetLogger("LoggerJieKou");
                            var phone = toPhone;
                            var shopName = shopModel["shop_name"];
                            //if (!string.IsNullOrWhiteSpace(phone))
                            //{
                            //    var i = SmsSendInterface.sendOnce(phone, "尊敬的用户您好，（" + shopName + "）商户给您下了一条新订单，请尽快进入青贯助手小程序查看。");

                            //    logJieKou.Info($"发送消息短信：{phone} 返回结果：{i}");
                            //}
                            //else
                            //{
                            //    logJieKou.Info($"发送消息短信：没有号码");
                            //}
                        }
                    }
                    #endregion

                    if (fileids.Count > 0)//卖家下单的产品临时图片
                        ConvertTemporary(mainsql, string.Join(",", fileids));

                    var xunjiaId = comrcv.Map_Args.ContainsKey("x_id") ? comrcv.Map_Args["x_id"] : string.Empty;
                    var xunjiaTime = comrcv.Map_Args.ContainsKey("x_time") ? comrcv.Map_Args["x_time"] : string.Empty;
                    if (!string.IsNullOrWhiteSpace(xunjiaId))
                    {
                        var time = (xunjiaTime.ToDateTime().Value.ToString("yyyy-MM").Substring(0, 7) + "-01").ToDateTime();
                        mainsql.SqlExcuteNoReturn($"update {BIAOXUNJIA + time.Value.ToString("yyyyMM")} set order_id='{order}' where x_id='{xunjiaId}'");
                    }
                    ret.Map_Args.Add("orderid", order.ToString());
                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 卖家确认买家的订单

        [WebMethod(Description = "卖家确认买家的订单")]
        public string Shop_OrderPriceSubmit(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_OrderPriceSubmit) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"]; //当前用户ID
                    var orderId = comrcv.Map_Args["OrderId"].ToLong(); //订单ID,必须主订单
                    var order_status = mainsql.SqlExecuteScalar($"select order_status from {BIAOORDER} where order_id={orderId}");
                    var daifu = comrcv.Map_Args["DaiFu"].ToInt32();

                    if (order_status == null || order_status.ToInt32() != 6)
                    {
                        ret.Map_Args["ErrorMsg"] = "订单不存在或订单已被操作过";
                        mainsql.closesql();
                        goto EXIT;
                    }

                    var shops = new List<Dictionary<string, object>>();
                    var fileids = new List<string>();
                    double sumPrice = 0;
                    double sumfreigth = 0;

                    #region 产品数据，产品、购物车
                    if (comrcv.Map_Args.ContainsKey("Shops"))
                    {
                        var jsonStr = comrcv.Map_Args["Shops"];
                        if (!string.IsNullOrWhiteSpace(jsonStr))
                        {
                            JArray json = JsonConvert.DeserializeObject<JArray>(jsonStr);

                            if (json != null && json.Count > 0)
                            {
                                foreach (var item in json)
                                {
                                    //产品ID、SKU、数量、单位、单价、运费、店铺ID
                                    var model = new Dictionary<string, object>();
                                    var pJson = item.Value<JArray>("Products");
                                    var ps = new List<Dictionary<string, object>>();
                                    foreach (var pItem in pJson)
                                    {
                                        var product = new Dictionary<string, object>();
                                        var price = pItem.Value<string>("Price").ToDouble();
                                        var number = pItem.Value<string>("Number").ToInt32();
                                        var freight = pItem.Value<string>("Freight").ToDouble();

                                        product.Add("ID", pItem.Value<string>("order_prd_id").ToLong()); //id 可空
                                        product.Add("ProductId", pItem.Value<string>("ProductId").ToLong()); //id 可空
                                        product.Add("Name", pItem.Value<string>("Name"));                    //名称 如果有id就可空
                                        product.Add("Sku", pItem.Value<string>("Sku") ?? string.Empty);      //sku，用户选择的产品配置 可空
                                        product.Add("Number", number);      //产品数量 必须
                                        product.Add("Unit", pItem.Value<string>("Unit"));                    //数量单位 可空
                                        product.Add("ShortDescript", pItem.Value<string>("ShortDescript"));                    //数量单位 可空
                                        product.Add("Price", price);       //产品单价 如果有id就可空
                                        product.Add("Freight", freight);   //当前产品总运费计算后的价格，0包邮 必须
                                        var fileid = pItem.Value<string>("Files");
                                        product.Add("CoverFile", fileid);
                                        if (!string.IsNullOrWhiteSpace(fileid))
                                            fileids.AddRange(fileid.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries));
                                        sumPrice += (price * number);
                                        sumfreigth += freight;
                                        ps.Add(product);
                                    }
                                    model.Add("ShopId", item.Value<string>("ShopId"));                //店铺ID 必须
                                    model.Add("Content", item.Value<string>("Content"));                //备注 可空
                                    model.Add("Products", ps);
                                    shops.Add(model);
                                }
                            }
                        }
                    }
                    #endregion

                    #region 添加子单信息
                    foreach (var item in shops)
                    {
                        var shopId = item["ShopId"]?.ToString();
                        var descript = item["Content"]?.ToString() ?? string.Empty;
                        if (string.IsNullOrWhiteSpace(shopId))
                        {
                            ret.Map_Args["ErrorMsg"] = "参数错误，店铺ID不能为空";
                            mainsql.closesql();
                            goto EXIT;
                        }
                        var shopModel = mainsql.SqlExcuteWithReturn($"select * from {BIAOSHOP} where shop_id='{shopId}'").ToModels().FirstOrDefault();
                        if (shopModel == null || !shopModel.ContainsKey("shop_status"))
                        {
                            ret.Map_Args["ErrorMsg"] = "数据错误，不存在的店铺";
                            mainsql.closesql();
                            goto EXIT;
                        }
                        if (shopModel["shop_status"].ToInt32() != 0)
                        {
                            ret.Map_Args["ErrorMsg"] = "店铺未开启，不允许下单";
                            mainsql.closesql();
                            goto EXIT;
                        }
                        var products = item["Products"] as List<Dictionary<string, object>>;
                        if (products.Count == 0)
                        {
                            ret.Map_Args["ErrorMsg"] = "参数错误，产品信息不存在";
                            mainsql.closesql();
                            goto EXIT;
                        }

                        foreach (var pItem in products)
                        {
                            var id = pItem["ID"].ToLong();
                            if (id > 0)
                            {
                                mainsql.SqlExcuteNoReturn($"delete from {BIAOORDERPRODUCT} where order_prd_id={id}");
                            }
                            //添加订单产品 addproduct
                            var produtId = pItem["ProductId"].ToLong();
                            if (produtId > 0)
                            {
                                //卖家店铺产品
                                string addSQL = $"insert into {BIAOORDERPRODUCT}(order_prd_cover_id,order_id,prd_id,order_prd_type_id,order_prd_sku,order_prd_number,order_prd_name,order_prd_short_descript,order_prd_descript,order_prd_logo_ids,order_prd_price,order_prd_unit,order_prd_create_time,order_prd_create_user,order_prd_freight) "
                                    + $"select prd_cover_id,{orderId},prd_id,prd_type_id,'{pItem["Sku"]}',{pItem["Number"].ToInt32()},prd_name,prd_short_descript,prd_descript,prd_logo_ids,prd_price,prd_unit,NOW(),'{userid}',{pItem["Freight"].ToDouble()} from {BIAOPRODUCT} where prd_id={produtId} and shop_id='{shopId}'";
                                if (mainsql.SqlExcuteNoReturn(addSQL) != 1)
                                {
                                    ret.Map_Args["ErrorMsg"] = "参数错误，店铺ID和产品ID不一致";
                                    mainsql.closesql();
                                    goto EXIT;
                                }
                            }
                            else
                            {
                                //卖家自定义产品
                                string addSQL = $"insert into {BIAOORDERPRODUCT}(order_id,order_prd_number,order_prd_name,order_prd_price,order_prd_unit,order_prd_create_time,order_prd_create_user,order_prd_freight,order_prd_sku,order_prd_cover_id,order_prd_short_descript,order_prd_logo_ids) "
                                    + "values(@OrderId,@ProductNumber,@Name,@Price,@Unit,NOW(),@UserId,@Freight,@Sku,@CoverFile,@ShortDescript,@fileids)";
                                var files = pItem["CoverFile"]?.ToString()?.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);

                                var paras2 = new List<MySqlParameter>();
                                paras2.Add(new MySqlParameter("@OrderId", orderId));
                                paras2.Add(new MySqlParameter("@Sku", pItem["Sku"]));
                                paras2.Add(new MySqlParameter("@ProductNumber", pItem["Number"].ToInt32()));
                                paras2.Add(new MySqlParameter("@Name", pItem["Name"]));
                                paras2.Add(new MySqlParameter("@Unit", pItem["Unit"]));
                                paras2.Add(new MySqlParameter("@CoverFile", files.Length == 0 ? "" : files.FirstOrDefault()));
                                paras2.Add(new MySqlParameter("@fileids", pItem["CoverFile"]));
                                paras2.Add(new MySqlParameter("@ShortDescript", pItem["ShortDescript"]));
                                paras2.Add(new MySqlParameter("@Price", pItem["Price"].ToDouble()));
                                paras2.Add(new MySqlParameter("@Freight", pItem["Freight"].ToDouble()));
                                paras2.Add(new MySqlParameter("@UserId", userid));
                                mainsql.SqlExcuteNoReturn(addSQL, paras2.ToArray());
                            }
                        }
                    }
                    #endregion

                    if (daifu == 0)
                    {
                        mainsql.SqlExcuteNoReturn($"update {BIAOORDER} set order_status=1,order_price={sumPrice},order_freight={sumfreigth},order_daifu={daifu},order_pay_method=1,order_pay_time=NOW() where order_parent_id={orderId} or order_id={orderId}");
                    }
                    else
                    {
                        mainsql.SqlExcuteNoReturn($"update {BIAOORDER} set order_status=0,order_price={sumPrice},order_freight={sumfreigth},order_daifu={daifu},order_pay_method=0 where order_parent_id={orderId} or order_id={orderId}");
                    }

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 根据订单号查询订单附加信息
        [WebMethod(Description = "根据订单号查询订单附加信息")]
        public string Shop_FindOrderAddById(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_FindOrderAddById) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                var orderId = comrcv.Map_Args["OrderId"].ToLong();
                if (orderId <= 0)
                {
                    ret.Map_Args["ErrorMsg"] = "订单号异常";
                    mainsql.closesql();
                    goto EXIT;
                }
                //类型:0：备注，1：评价，2：申请取消
                var addType = comrcv.Map_Args["AddType"].ToInt32();

                string sql = $"select * from {BIAOORDERADD} where order_id={orderId} and order_add_type={addType} order by order_add_create_time";
                var models = mainsql.SqlExcuteWithReturn(sql).ToModels();
                if (models.Count > 0)
                {
                    var ids = new List<string>();
                    models.Where(x => !string.IsNullOrWhiteSpace(x["order_add_file_ids"])).ToList().ForEach(x =>
                    {
                        ids.AddRange(x["order_add_file_ids"].Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries));
                    });
                    if (ids.Count > 0)
                    {
                        sql = $"select file_id,file_small_path,file_path from {BIAOSHOPFILE} where file_id in ('{string.Join("','", ids)}')";
                        ret.Maplist_MapArgs.Add("Files", mainsql.SqlExcuteWithReturn(sql).ToModels());
                    }
                }
                ret.Maplist_MapArgs.Add("Datas", models);
                ret.Map_Args["ErrorMsg"] = "成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 分页查询店铺评价列表
        [WebMethod(Description = "分页查询店铺评价列表")]
        public string Shop_GetOrderScoreByPage(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetOrderScoreByPage) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                var pageIndex = comrcv.Map_Args["pageIndex"].ToInt32();
                pageIndex = pageIndex == 0 ? 1 : pageIndex;
                var pageSize = comrcv.Map_Args["pageSize"].ToInt32();
                pageSize = pageSize == 0 ? 10 : pageSize;

                var shopId = comrcv.Map_Args["ShopId"];
                if (string.IsNullOrWhiteSpace(shopId))
                {
                    ret.Map_Args["ErrorMsg"] = "参数异常";
                    mainsql.closesql();
                    goto EXIT;
                }

                StringBuilder sql = new StringBuilder();
                sql.AppendFormat("select t1.*,t2.order_score from {2} t1 inner join (select order_id,order_score from {0} where order_deleteflag=0 and shop_id='{1}') t2 on t1.order_id=t2.order_id and order_add_type=1 and (order_add_parent_id is null or order_add_parent_id=0)", BIAOORDER, shopId, BIAOORDERADD);
                sql.AppendFormat(" order by t1.order_add_create_time desc limit {0},{1}", pageSize * pageIndex - pageSize, pageSize);

                var models = mainsql.SqlExcuteWithReturn(sql.ToString()).ToModels();

                if (models.Count > 0)
                {
                    var ids = new List<string>();
                    models.ForEach(x =>
                    {
                        if (!string.IsNullOrWhiteSpace(x["order_add_file_ids"]))
                        {
                            ids.AddRange(x["order_add_file_ids"].Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries));
                        }
                    });
                    if (ids.Count > 0)
                    {
                        var files = mainsql.SqlExcuteWithReturn($"select file_id,file_path from {BIAOSHOPFILE} where file_id in('{string.Join("','", ids)}')").ToModels();

                        ret.Maplist_MapArgs.Add("Files", files);
                    }
                }

                ret.Maplist_MapArgs.Add("Order", models);
                ret.Map_Args["ErrorMsg"] = "成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 卖家查询待发货订单数量
        [WebMethod(Description = "卖家查询待发货订单数量")]
        public string Shop_Getfahuonumber(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_Getfahuonumber) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                var shopId = comrcv.Map_Args["ShopId"];

                var result = mainsql.SqlExcuteWithReturn($"select count(1) count,order_status from {BIAOORDER} where shop_id='{shopId}' group by order_status").ToModels();
                var fukuan = string.Empty;
                var fahuo = string.Empty;
                var shouhuo = string.Empty;
                foreach (var item in result)
                {
                    if (item["order_status"] == "0")
                    {
                        fukuan = item["count"];
                    }
                    else if (item["order_status"] == "1")
                    {
                        fahuo = item["count"];
                    }
                    else if (item["order_status"] == "2")
                    {
                        shouhuo = item["count"];
                    }
                }

                var carids = mainsql.SqlExcuteWithReturn($"select car_type_id from {BIAOSHOPCAR} where shop_id='{shopId}'").ToModels().Select(x => x["car_type_id"]).ToList();
                var shopTag = mainsql.SqlExcuteWithReturn($"select shop_ation,allxunjia from {BIAOSHOP} t1 left join s_allshop t2 on t1.shop_id=t2.shop_id where t1.shop_id='{shopId}'").ToModels().FirstOrDefault();
                var list = new List<Dictionary<string, string>>();
                int baojiacount = 0;
                if (carids.Count > 0)
                {
                    var starttime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                    var endtime = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
                    var datas = mainsql.SqlExcuteWithReturn($"select t1.*,tg_tag from {BIAOXUNJIA + DateTime.Now.ToString("yyyyMM")} t1 left join {BIAOUSER} t2 on t1.user_id=t2.user_onlyid left join {BIAOUSERCOMPANY} t3 on t2.companyid=t3.user_id left join {BIAOSHOP} t4 on t3.user_tuiguangma=t4.shop_tuiguangma left join s_allshop t5 on t4.shop_id=t5.shop_id where t1.x_deleteflag=0 and t1.x_send_time >='{starttime}' and t1.x_send_time<'{endtime}' order by t1.x_send_time desc").ToModels();
                    foreach (var item in datas)
                    {
                        if (shopTag["allxunjia"].ToInt32() == 1)
                        {
                            list.Add(item);
                            continue;
                        }
                        var istrue = true;
                        //if (!string.IsNullOrWhiteSpace(item["tg_tag"]))
                        //{
                        //    if (shopTag["shop_ation"]?.Contains(item["tg_tag"]) == true)
                        //        istrue = true;
                        //    else istrue = false;
                        //}
                        if (istrue)
                        {
                            istrue = false;
                            carids.ForEach(x => { if (!istrue) istrue = item["x_car_id"].IndexOf(x) != -1; });
                        }
                        if (istrue)
                        {
                            list.Add(item);
                        }
                    }
                    if (list.Count > 0)
                    {
                        var ids = string.Join("','", list.Select(x => x["x_id"]));
                        baojiacount = mainsql.SqlExecuteScalar($"select count(1) from {BIAOBAOJIA + DateTime.Now.ToString("yyyyMM")} where x_id in ('{ids}') and shop_id='{shopId}'").ToInt32();
                    }
                }

                var weixiucount = mainsql.SqlExecuteScalar(string.Format("select  count(*) from {0} where repair_shopid='{1}' AND repair_status1<>'6'  ;", BIAOUSERREPAIR, shopId)).ToInt32();
                var orderCount = mainsql.SqlExecuteScalar($"SELECT count(*) from s_order where shop_id = '{shopId}' and(order_status = 1 || order_status = 0);").ToInt32();//订单数
                var orderSameDayCount = mainsql.SqlExecuteScalar($"SELECT count(*) from s_order where shop_id='{shopId}' and order_create_time like '{DateTime.Now.ToString("yyyy-MM-dd")}%'").ToInt32();//获取当日订单统计
                var repairSameDayCount = mainsql.SqlExecuteScalar($"SELECT count(*) from s_userrepair where repair_shopid='{shopId}' and repair_createtime like '{DateTime.Now.ToString("yyyy-MM-dd")}%'").ToInt32();//获取当日维修订单统计
                var orderData = mainsql.SqlExcuteWithReturn($@" select SUM(orderCount) as orderCount,SUM(orderPrice) as orderPrice from 
                        (SELECT  count(*) as orderCount, IFNULL(SUM(repair_allprice), '0') as orderPrice  from s_userrepair where repair_status1 = '6' and repair_shopid = '{shopId}'
                        and repair_overtime like '{DateTime.Now.ToString("yyyy-MM-dd")}%'
                        UNION
                        SELECT  count(*) as orderCount, IFNULL(SUM(order_price), '0') as orderPrice  from s_order where order_status = '3' and shop_id = '{shopId}'
                        and order_confirm_time like '{DateTime.Now.ToString("yyyy-MM-dd")}%') a").ToModels().FirstOrDefault();

                ret.Map_Args.Add("WeiXiuCount", weixiucount.ToString());
                ret.Map_Args.Add("XunJiaCount", list.Count.ToString());
                ret.Map_Args.Add("BaoJiaCount", baojiacount.ToString());
                ret.Map_Args.Add("OrderCount", orderCount.ToString());//货架订单
                ret.Map_Args.Add("SameDayOrderCount", (orderSameDayCount + repairSameDayCount).ToString());//今日订单数量
                ret.Map_Args.Add("SameDayCompleteOrder", orderData["orderCount"].ToString());//订单完成到账
                ret.Map_Args.Add("SameDayMoney", orderData["orderPrice"].ToString());//今日订单到账

                ret.Map_Args.Add("fukuan", fukuan);
                ret.Map_Args.Add("fahuo", fahuo);
                ret.Map_Args.Add("shouhuo", shouhuo);



                ret.Map_Args["ErrorMsg"] = "成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 买家查询待发货订单数量
        [WebMethod(Description = "买家查询待发货订单数量")]
        public string Shop_GetOrdernumberBuyer(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetOrdernumberBuyer) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                var userId = comrcv.Map_Args["userid"];

                var result = mainsql.SqlExcuteWithReturn($"select count(1) count,order_status from {BIAOORDER} where order_to_user_id='{userId}' group by order_status").ToModels();
                var fukuan = "0";
                var fahuo = "0";
                var shouhuo = "0";
                foreach (var item in result)
                {
                    if (item["order_status"] == "0")
                    {
                        fukuan = item["count"];
                    }
                    else if (item["order_status"] == "1")
                    {
                        fahuo = item["count"];
                    }
                    else if (item["order_status"] == "2")
                    {
                        shouhuo = item["count"];
                    }
                }

                //团购订单
                var sql = $"select count(*) from  s_commoditybuyorder where buy_order_status=0 and (buy_order_pay_status=1||buy_order_pay_status=6) and user_id='{userId}';";
                var commodityCount = mainsql.SqlExecuteScalar(sql).ToInt32();
                ret.Map_Args["WriteOffCount"] = commodityCount.ToString();

                //维修订单
                sql = $"select count(1) from s_userrepair where repair_status1<>6 and repair_yonghuid ='{userId}';";
                var repairCount = mainsql.SqlExecuteScalar(sql).ToInt32();
                ret.Map_Args["UserRepairCount"] = repairCount.ToString();

                //优惠券
                var couponCount = mainsql.SqlExecuteScalar($"select  count(1) from s_coupon where coupon_status=0 and user_id='{userId}'").ToInt32();
                ret.Map_Args["CouponCount"] = couponCount.ToString();

                ret.Map_Args.Add("fukuan", fukuan);
                ret.Map_Args.Add("fahuo", fahuo);
                ret.Map_Args.Add("shouhuo", shouhuo);

                //购物车
                var collproductCount = mainsql.SqlExecuteScalar($"select  count(1) from s_collproduct where user_id='{userId}'").ToInt32();

                //订单总数量
                ret.Map_Args["orderCount"] = (commodityCount + repairCount + (int.Parse(fukuan) + int.Parse(fahuo) + int.Parse(shouhuo))).ToString();
                //购物车数量
                ret.Map_Args.Add("collproductCount", collproductCount.ToString());

                ret.Map_Args["ErrorMsg"] = "成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 根据订单号查询订单信息(卖家)
        [WebMethod(Description = "根据订单号查询订单信息(卖家)")]
        public string Shop_FindOrderByIdShop(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_FindOrderByIdShop) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                var shopId = comrcv.Map_Args["ShopId"];
                var orderId = comrcv.Map_Args["OrderId"].ToLong();
                if (orderId <= 0)
                {
                    ret.Map_Args["ErrorMsg"] = "订单号异常";
                    mainsql.closesql();
                    goto EXIT;
                }
                string sql = $"select t1.*,t2.order_add_content from {BIAOORDER} t1 left join {BIAOORDERADD} t2 on t1.order_id=t2.order_id and order_add_type=0 where (t1.order_id={orderId} or order_parent_id={orderId}) and shop_id='{shopId}' and order_deleteflag=0";
                var models = mainsql.SqlExcuteWithReturn(sql).ToModels();
                var model = models.FirstOrDefault(x => x["order_id"].ToLong() == orderId);
                if (model == null)
                {
                    ret.Map_Args["ErrorMsg"] = "订单不存在或已被删除";
                    mainsql.closesql();
                    goto EXIT;
                }

                sql = $"select t1.*,t3.file_path as ProductFilePath from {BIAOORDERPRODUCT} t1 left join (select * from {BIAOORDER} where (order_id={orderId} or order_parent_id={orderId}) and order_deleteflag=0) t2 on t1.order_id=t2.order_id left join {BIAOSHOPFILE} t3 on t1.order_prd_cover_id=t3.file_id where t2.order_id>0";

                ret.Maplist_MapArgs.Add("Products", mainsql.SqlExcuteWithReturn(sql).ToModels());

                sql = $"select * from {BIAOORDERSALE} where order_id={orderId} order by sa_createtime";
                ret.Maplist_MapArgs.Add("OrderSale", mainsql.SqlExcuteWithReturn(sql).ToModels());

                #region 查询运单详情
                if ("0".Equals(model["order_ems"]))
                {
                    var ydnumber = model["order_ems_number"];
                    if (!string.IsNullOrWhiteSpace(ydnumber))
                    {
                        var ems = new
                        {
                            funcId = "order.getbyyuyue",
                            orderno = ydnumber,
                        };
                        var poststr = JsonConvert.SerializeObject(ems);
                        var result = SmsSendInterface.postJson(_addOrderUrl, poststr);
                        ret.Map_Args.Add("OrderYD", result);
                    }
                }
                #endregion
                ret.Maplist_MapArgs.Add("Order", models);
                ret.Map_Args["ErrorMsg"] = "成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 根据订单号查询订单信息(买家)
        [WebMethod(Description = "根据订单号查询订单信息(买家)")]
        public string Shop_FindOrderByIdBuyer(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_FindOrderByIdBuyer) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                var orderId = comrcv.Map_Args["OrderId"].ToLong();
                if (orderId <= 0)
                {
                    ret.Map_Args["ErrorMsg"] = "订单号异常";
                    mainsql.closesql();
                    goto EXIT;
                }
            First:
                string sql = $"select t1.*,t2.order_add_content from {BIAOORDER} t1 left join {BIAOORDERADD} t2 on t1.order_id=t2.order_id and order_add_type=0 where (t1.order_id={orderId} or order_parent_id={orderId}) and order_deleteflag=0";
                var models = mainsql.SqlExcuteWithReturn(sql).ToModels();
                if (models.Count == 0)
                {
                    ret.Map_Args["ErrorMsg"] = "订单不存在或已被删除";
                    mainsql.closesql();
                    goto EXIT;
                }
                var model = models.FirstOrDefault(x => x["order_id"].ToLong() == orderId);
                if (model == null)
                {
                    //订单号是子订单，查找主订单，返回主订单信息
                    orderId = models.FirstOrDefault(x => x["order_parent_id"].ToLong() > 0)["order_parent_id"].ToLong();
                    goto First;
                }

                sql = $"select t1.*,t3.file_path as ProductFilePath from {BIAOORDERPRODUCT} t1 left join (select * from {BIAOORDER} where (order_id={orderId} or order_parent_id={orderId}) and order_deleteflag=0) t2 on t1.order_id=t2.order_id left join {BIAOSHOPFILE} t3 on t1.order_prd_cover_id=t3.file_id where t2.order_id>0";

                ret.Maplist_MapArgs.Add("Products", mainsql.SqlExcuteWithReturn(sql).ToModels());

                sql = $"select * from {BIAOORDERSALE} where order_id={orderId} order by sa_createtime";
                ret.Maplist_MapArgs.Add("OrderSale", mainsql.SqlExcuteWithReturn(sql).ToModels());
                #region 查询运单详情
                if ("0".Equals(model["order_ems"]))
                {
                    var ydnumber = model["order_ems_number"];
                    if (!string.IsNullOrWhiteSpace(ydnumber))
                    {
                        var ems = new
                        {
                            funcId = "order.getbyyuyue",
                            orderno = ydnumber,
                        };
                        var poststr = JsonConvert.SerializeObject(ems);
                        var result = SmsSendInterface.postJson(_addOrderUrl, poststr);
                        ret.Map_Args.Add("OrderYD", result);
                    }
                }
                #endregion
                ret.Maplist_MapArgs.Add("Order", models);
                ret.Map_Args.Add("OrderId", orderId.ToString());
                ret.Map_Args["ErrorMsg"] = "成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 分页查询订单列表
        [WebMethod(Description = "分页查询订单列表")]
        public string Shop_GetOrderByPage(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetOrderByPage) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                var pageIndex = comrcv.Map_Args["pageIndex"].ToInt32();
                pageIndex = pageIndex == 0 ? 1 : pageIndex;
                var pageSize = comrcv.Map_Args["pageSize"].ToInt32();
                pageSize = pageSize == 0 ? 10 : pageSize;


                var userId = comrcv.Map_Args.ContainsKey("userid") ? comrcv.Map_Args["userid"] : string.Empty;
                var shopId = comrcv.Map_Args.ContainsKey("ShopId") ? comrcv.Map_Args["ShopId"] : string.Empty;
                if (string.IsNullOrWhiteSpace(userId) && string.IsNullOrWhiteSpace(shopId))
                {
                    ret.Map_Args["ErrorMsg"] = "参数异常";
                    mainsql.closesql();
                    goto EXIT;
                }

                StringBuilder sql = new StringBuilder();
                sql.AppendFormat("select t1.*,t2.shop_name as ShopName,t3.file_small_path as ShopTitlePath,t4.sa_status from {0} t1 "
                    + "left join {1} t2 on t1.shop_id=t2.shop_id "
                    + "left join {2} t3 on t2.shop_title_id=t3.file_id "
                    + "left join (select order_id,0 as sa_status from {3} where sa_status<>1 group by order_id) t4 on t1.order_id=t4.order_id where t1.order_deleteflag=0", BIAOORDER, BIAOSHOP, BIAOSHOPFILE, BIAOORDERSALE);

                if (!string.IsNullOrWhiteSpace(userId))
                {
                    sql.AppendFormat(" and order_to_user_id='{0}'", userId);
                }
                if (!string.IsNullOrWhiteSpace(shopId))
                {
                    sql.AppendFormat(" and t1.shop_id='{0}'", shopId);
                }

                if (comrcv.Map_Args.ContainsKey("Status"))
                {
                    //订单状态：0新订单，1已付款，2已发货，3确认收货，4申请取消，5已取消
                    var status = comrcv.Map_Args["Status"].ToInt32();
                    sql.Append(" and t1.order_status=" + status);
                    if (status == 0)
                    {
                        //新订单只查询主单
                        sql.Append(" and order_parent_id is null");
                    }
                    else
                    {
                        //不查新订单，查询有店铺的订单
                        sql.Append(" and t1.shop_id is not null");
                    }
                }

                if (comrcv.Map_Args.ContainsKey("startime"))
                {
                    sql.AppendFormat(" and t1.order_create_time>='{0}'", comrcv.Map_Args["startime"]);
                }
                if (comrcv.Map_Args.ContainsKey("endtime"))
                {
                    sql.AppendFormat(" and t1.order_create_time<='{0}'", comrcv.Map_Args["endtime"].ToDateTime().Value.AddDays(1).ToString("yyyy-MM-dd"));
                }

                string sqlStr = $"select t1.*,t3.file_small_path as ProductTitlePath from {BIAOORDERPRODUCT} t1 left join ({sql.ToString()}) t2 on t1.order_id=t2.order_id left join {BIAOSHOPFILE} t3 on t1.order_prd_cover_id=t3.file_id where t2.order_id>0";
                sql.AppendFormat(" order by t1.order_create_time desc limit {0},{1}", pageSize * pageIndex - pageSize, pageSize);

                var models = mainsql.SqlExcuteWithReturn(sql.ToString()).ToModels();

                if (models.Count > 0)
                {
                    ret.Maplist_MapArgs.Add("Products", mainsql.SqlExcuteWithReturn(sqlStr).ToModels());
                }
                if (!string.IsNullOrWhiteSpace(shopId))
                {
                    var yydd = new Dictionary<string, string>();
                    var yd = new Dictionary<string, string>();
                    foreach (var item in models)
                    {
                        if ("1".Equals(item["order_pay_method"])
                            && "2".Equals(item["order_status"])
                            && "0".Equals(item["order_ems"]))
                        {
                            if (string.IsNullOrWhiteSpace(item["order_ems_number2"]))
                            {
                                if (!yydd.ContainsKey(item["order_ems_number"]))
                                    yydd.Add(item["order_ems_number"], item["order_ems_name"]);
                            }
                            else
                            {
                                if (!yd.ContainsKey(item["order_ems_number2"]))
                                    yd.Add(item["order_ems_number2"], item["order_ems_name"]);
                            }
                        }
                    }
                    #region 通过预约单号查询运单号
                    if (yydd.Count > 0)
                    {
                        foreach (var item in yydd.GroupBy(x => x.Value))
                        {
                            var ems = new
                            {
                                funcId = "order.getwuliuidbyyuyue",
                                companyaccount = item.Key,  //物流公司账号
                                ordernos = string.Join(",", item.Select(x => x.Key)),     //预约单号
                            };
                            var poststr = JsonConvert.SerializeObject(ems);
                            var result = SmsSendInterface.postJson(_addOrderUrl, poststr);
                            var json = Newtonsoft.Json.Linq.JToken.Parse(result);
                            if (json.Value<int>("code") == 1)
                            {
                                foreach (var keyItem in item.Select(x => x.Key))
                                {
                                    var ydnumber = json.Value<string>(keyItem);
                                    if (!string.IsNullOrWhiteSpace(ydnumber) && !"没有被承运".Equals(ydnumber))
                                    {
                                        if (!yd.ContainsKey(ydnumber))
                                            yd.Add(ydnumber, item.Key);
                                        mainsql.SqlExcuteNoReturn($"update s_order set order_ems_number2='{ydnumber}' where order_ems_number='{keyItem}'");
                                        foreach (var modelItem in models)
                                        {
                                            if (keyItem.Equals(modelItem["order_ems_number"]))
                                            {
                                                modelItem["order_ems_number2"] = ydnumber;
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                loginfo.Info(poststr);
                                loginfo.Info(result);
                            }
                        }
                    }
                    #endregion

                    #region 通过运单号查询代收状态
                    if (yd.Count > 0)
                    {
                        foreach (var item in yd.GroupBy(x => x.Value))
                        {
                            var ems = new
                            {
                                funcId = "order.getdaishou",
                                companyaccount = item.Key,  //物流公司账号
                                biaoids = string.Join(",", item.Select(x => x.Key)),     //运单号
                            };
                            var poststr = JsonConvert.SerializeObject(ems);
                            var result = SmsSendInterface.postJson(_addOrderUrl, poststr);
                            var json = Newtonsoft.Json.Linq.JToken.Parse(result);
                            if (json.Value<int>("code") == 1)
                            {
                                var jar = json.Value<JArray>("data");
                                foreach (var jItem in jar)
                                {
                                    foreach (var modelItem in models)
                                    {
                                        if (jItem.Value<string>("Biao_Id").Equals(modelItem["order_ems_number2"]))
                                        {
                                            modelItem.Add("Biao_Status", jItem.Value<string>("Biao_Status"));
                                        }
                                    }
                                }
                            }
                            else
                            {
                                loginfo.Info(poststr);
                                loginfo.Info(result);
                            }
                        }
                    }
                    #endregion
                }
                ret.Maplist_MapArgs.Add("Order", models);
                ret.Map_Args["ErrorMsg"] = "成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion


        #region 分页查询单位内订单列表
        [WebMethod(Description = "分页查询单位内订单列表")]
        public string Shop_GetOrderByConpanyPage(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetOrderByPage) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                var pageIndex = comrcv.Map_Args["pageIndex"].ToInt32();
                pageIndex = pageIndex == 0 ? 1 : pageIndex;
                var pageSize = comrcv.Map_Args["pageSize"].ToInt32();
                pageSize = pageSize == 0 ? 10 : pageSize;

                var companyid = comrcv.Map_Args["companyid"];
                if (string.IsNullOrWhiteSpace(companyid))
                {
                    ret.Map_Args["ErrorMsg"] = "参数异常";
                    mainsql.closesql();
                    goto EXIT;
                }

                StringBuilder sql = new StringBuilder();
                sql.AppendFormat("select t1.*,t2.shop_name as ShopName,t3.file_small_path as ShopTitlePath,t4.sa_status from {0} t1 "
                    + "left join {1} t2 on t1.shop_id=t2.shop_id "
                    + "left join {2} t3 on t2.shop_title_id=t3.file_id "
                    + $"inner join {BIAOUSER} u on t1.order_to_user_id=u.user_onlyid and u.companyid='{companyid}' "
                    + "left join (select order_id,0 as sa_status from {3} where sa_status<>1 group by order_id) t4 on t1.order_id=t4.order_id where t1.order_deleteflag=0", BIAOORDER, BIAOSHOP, BIAOSHOPFILE, BIAOORDERSALE);

                string sqlStr = $"select t1.*,t3.file_small_path as ProductTitlePath from {BIAOORDERPRODUCT} t1 left join ({sql.ToString()}) t2 on t1.order_id=t2.order_id left join {BIAOSHOPFILE} t3 on t1.order_prd_cover_id=t3.file_id where t2.order_id>0";
                sql.AppendFormat(" order by t1.order_create_time desc limit {0},{1}", pageSize * pageIndex - pageSize, pageSize);

                var models = mainsql.SqlExcuteWithReturn(sql.ToString()).ToModels();

                if (models.Count > 0)
                {
                    ret.Maplist_MapArgs.Add("Products", mainsql.SqlExcuteWithReturn(sqlStr).ToModels());
                }

                ret.Maplist_MapArgs.Add("Order", models);
                ret.Map_Args["ErrorMsg"] = "成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 根据订单号取消订单(需要退款，未完成)

        [WebMethod(Description = "根据订单号取消订单")]
        public string Shop_CancelOrder(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_CancelOrder) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"]; //当前用户
                    var orderId = comrcv.Map_Args["OrderId"].ToLong(); //订单ID
                    var type = comrcv.Map_Args["type"].ToInt32();//0：买家取消；1：卖家取消
                    var parentid = comrcv.Map_Args.ContainsKey("order_add_id") ? comrcv.Map_Args["order_add_id"] : string.Empty; //申请取消的ID
                    var descript = comrcv.Map_Args.ContainsKey("Content") ? comrcv.Map_Args["Content"] : string.Empty; //取消原因
                    var orderModel = mainsql.SqlExcuteWithReturn($"select * from {BIAOORDER} where order_id={orderId}").ToModels().FirstOrDefault();
                    if (orderModel == null)
                    {
                        ret.Map_Args["ErrorMsg"] = "订单不存在";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    var orderstatus = orderModel["order_status"].ToInt32();
                    var paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@OrderId", orderId));
                    paras.Add(new MySqlParameter("@userid", userid));
                    paras.Add(new MySqlParameter("@Content", descript));
                    paras.Add(new MySqlParameter("@status", orderstatus));
                    if (string.IsNullOrWhiteSpace(parentid))
                    {
                        paras.Add(new MySqlParameter("@parentid", MySqlDbType.Int64) { Value = null });
                    }
                    else
                        paras.Add(new MySqlParameter("@parentid", parentid));

                    var model = mainsql.SqlExcuteWithReturn($"select * from {BIAOORDER} where order_id={orderId} and order_deleteflag=0").ToModels().FirstOrDefault();

                    mainsql.SqlExcuteNoReturn($"insert into {BIAOORDERADD}(order_id,order_add_create_time,order_add_create_user,order_status,order_add_type,order_add_content,order_add_parent_id)values(@OrderId,NOW(),@userid,@status,2,@Content,@parentid)", paras.ToArray());
                    if (type == 0)
                    {
                        if (model["order_status"].ToInt32() == 0)
                        {
                            mainsql.SqlExcuteNoReturn($"update {BIAOORDER} set order_status=5,order_sq_cancel_time=NOW(),order_cancel_time=NOW() where order_id={orderId}");
                        }
                        else
                        {
                            mainsql.SqlExcuteNoReturn($"update {BIAOORDER} set order_status=4,order_sq_cancel_time=NOW() where order_id={orderId}");
                        }
                    }
                    else
                    {
                        //todo 卖家取消订单需要退款
                        //信用付退款
                        if (orderModel["order_pay_method"].ToInt32() == 2 && orderModel["order_pay_status"].ToInt32() == 2)
                        {
                            if (orderModel["order_pay_time"].ToDateTime().Value.AddHours(72) <= DateTime.Now)
                            {
                                ret.Map_Args["ErrorMsg"] = "发货超过72小时不能取消订单";
                                mainsql.closesql();
                                goto EXIT;
                            }
                            var paramMap = new Dictionary<string, object>();
                            paramMap.Add("notify_status", "3");
                            paramMap.Add("cancel_apply_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            var status = setOrderStatus(model["order_number"], model["order_ch_number"], paramMap);
                            loginfo.Info("信用付退款返回状态:" + status);
                            if (status == 0 || status == 6 || status == 5 || status == 7)
                            {
                                mainsql.SqlExcuteNoReturn($"update {BIAOORDER} set order_status=5,order_sq_cancel_time=NOW(),order_cancel_time=NOW() where order_id={orderId}");
                            }
                        }
                        else
                        {
                            mainsql.SqlExcuteNoReturn($"update {BIAOORDER} set order_status=5,order_sq_cancel_time=NOW(),order_cancel_time=NOW() where order_id={orderId}");
                        }
                    }
                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 卖家否定取消

        [WebMethod(Description = "卖家否定取消")]
        public string Shop_CancelOrderNo(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_CancelOrderNo) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"]; //当前用户
                    var orderId = comrcv.Map_Args["OrderId"].ToLong(); //订单ID
                    var parentid = comrcv.Map_Args["order_add_id"];//申请取消的ID
                    var descript = comrcv.Map_Args.ContainsKey("Content") ? comrcv.Map_Args["Content"] : string.Empty; //取消原因
                    var orderModel = mainsql.SqlExcuteWithReturn($"select * from {BIAOORDERADD} where order_id={orderId} and order_status is not null order by order_add_create_time desc").ToModels().FirstOrDefault();
                    if (orderModel == null)
                    {
                        ret.Map_Args["ErrorMsg"] = "申请记录不存在";
                        mainsql.closesql();
                        goto EXIT;
                    }

                    var paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@OrderId", orderId));
                    paras.Add(new MySqlParameter("@userid", userid));
                    paras.Add(new MySqlParameter("@Content", descript));
                    if (string.IsNullOrWhiteSpace(parentid))
                    {
                        paras.Add(new MySqlParameter("@parentid", MySqlDbType.Int64) { Value = null });
                    }
                    else
                        paras.Add(new MySqlParameter("@parentid", parentid));

                    mainsql.SqlExcuteNoReturn($"insert into {BIAOORDERADD}(order_id,order_add_create_time,order_add_create_user,order_add_type,order_add_content,order_add_parent_id)values(@OrderId,NOW(),@userid,2,@Content,@parentid)", paras.ToArray());

                    mainsql.SqlExcuteNoReturn($"update {BIAOORDER} set order_status={orderModel["order_status"]},order_sq_cancel_time=NOW() where order_id={orderId}");

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 修改订单金额、支付方式、收货信息

        [WebMethod(Description = "修改订单金额、支付方式、收货信息")]
        public string Shop_UpdatePrice(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_UpdatePrice) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"]; //操作人
                    var orderId = comrcv.Map_Args["OrderId"].ToLong(); //订单ID
                    var price = comrcv.Map_Args["price"].ToDouble(); //订单金额
                                                                     //2021年3月26日 新增修改支付方式、修改收货人信息
                    int? pay = comrcv.Map_Args.ContainsKey("DaiFu") ? comrcv.Map_Args["DaiFu"].ToInt32Null() : null;//0支持代付，1不支持
                    var toAddress = comrcv.Map_Args.ContainsKey("ToAddress") ? comrcv.Map_Args["ToAddress"] : string.Empty; //收货地址
                    var toPhone = comrcv.Map_Args.ContainsKey("ToPhone") ? comrcv.Map_Args["ToPhone"] : string.Empty; //收货电话
                    var toUser = comrcv.Map_Args.ContainsKey("ToUser") ? comrcv.Map_Args["ToUser"] : string.Empty; //收货人名

                    //状态必须是新订单，同时付款状态必须是未付款
                    var orderModel = mainsql.SqlExcuteWithReturn($"select * from {BIAOORDER} where order_id={orderId} and order_deleteflag=0 and (order_status=0 or (order_pay_method=1 and order_status<2)) and order_pay_status=0").ToModels().FirstOrDefault();
                    if (orderModel == null)
                    {
                        ret.Map_Args["ErrorMsg"] = "订单错误或订单已付款";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    var shopId = orderModel["shop_id"];
                    var paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@userid", userid));
                    paras.Add(new MySqlParameter("@ShopId", shopId));
                    var count = mainsql.SqlExecuteScalar($"select count(1) from {BIAOSHOPUSER} where user_id=@userid and shop_id=@ShopId and shop_user_deleteflag=0", paras.ToArray()).ToInt32();
                    if (count == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "没有该店铺的操作权限";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    paras.Add(new MySqlParameter("@OrderId", orderId));
                    paras.Add(new MySqlParameter("@price", price));
                    if (pay != null)
                    {
                        paras.Add(new MySqlParameter("@toAddress", toAddress));
                        paras.Add(new MySqlParameter("@toPhone", toPhone));
                        paras.Add(new MySqlParameter("@toUser", toUser));
                        if (pay.Value == 0)
                        {
                            //订单待发货，支持代付，支付方式代付
                            mainsql.SqlExcuteNoReturn($"update {BIAOORDER} set order_price=@price,order_daifu='0',order_pay_method='1',order_status='1',order_pay_time=NOW(),order_to_address=@toAddress,order_to_phone=@toPhone,order_to_user=@toUser where order_id=@OrderId", paras.ToArray());
                        }
                        else
                        {
                            mainsql.SqlExcuteNoReturn($"update {BIAOORDER} set order_price=@price,order_daifu='1',order_to_address=@toAddress,order_to_phone=@toPhone,order_to_user=@toUser,order_pay_method=0,order_status=0 where order_id=@OrderId", paras.ToArray());
                        }
                    }
                    else
                    {
                        mainsql.SqlExcuteNoReturn($"update {BIAOORDER} set order_price=@price where order_id=@OrderId", paras.ToArray());
                    }
                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 根据订单号货到付款

        [WebMethod(Description = "根据订单号货到付款")]
        public string Shop_OrderDaiFu(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_OrderDaiFu) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var orderId = comrcv.Map_Args["OrderId"].ToLong(); //订单ID,必须主订单
                    var orderModel = mainsql.SqlExcuteWithReturn($"select order_daifu,order_price,user_name,user_phone from {BIAOORDER} t1 left join {BIAOUSER} t2 on t1.order_to_user_id=t2.user_onlyid where order_id='{orderId}'").ToModels().FirstOrDefault();
                    var daifu = orderModel["order_daifu"].ToInt32();
                    var price = orderModel["order_price"].ToDouble();
                    if (daifu > 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "订单不支持货到付款";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    mainsql.SqlExcuteNoReturn($"update {BIAOORDER} set order_status=1,order_pay_status=1,order_pay_method=1,order_pay_time=NOW() where order_parent_id={orderId} or order_id={orderId}");
                    var shopModel = mainsql.SqlExcuteWithReturn($"select t1.shop_id,shop_name,shop_tel_number,shop_tel_number2,t1.shop_id from {BIAOSHOP} t1 inner join {BIAOORDER} t2 on t1.shop_id=t2.shop_id where order_parent_id={orderId} or order_id={orderId}").ToModels().FirstOrDefault();
                    if (shopModel == null)
                    {
                        ret.Map_Args["ErrorMsg"] = "找不到店铺";
                        mainsql.closesql();
                        goto EXIT;
                    }

                    #region 发短信
                    ILog logJieKou = LogManager.GetLogger("LoggerJieKou");
                    var phone = shopModel["shop_tel_number"];
                    var shopName = shopModel["shop_name"];

                    //if (!string.IsNullOrWhiteSpace(phone))
                    //{
                    //    var i = SmsSendInterface.sendOnce(phone, "尊敬的（" + shopName + "）商户您好，您的店铺有一条新的订单（货到付款），请尽快进入青贯助手小程序查看发货。");

                    //    logJieKou.Info($"发送消息短信：{phone} 返回结果：{i}");
                    //}
                    //else
                    //{
                    //    logJieKou.Info($"发送消息短信：没有号码");
                    //}
                    #endregion

                    #region 发微信消息
                    var users = mainsql.SqlExcuteWithReturn($"select t2.user_openid_juhesheng,t2.user_phone,t2.user_name from {BIAOSHOPUSER} t1 left join {BIAOUSER} t2 on t1.user_id=t2.user_onlyid where shop_id='{shopModel["shop_id"]}' and shop_user_ismsg=1 and shop_user_deleteflag<>1").ToModels();

                    phone = orderModel["user_phone"];
                    var name = orderModel["user_name"];
                    foreach (var item in users)
                    {
                        var openid = item["user_openid_juhesheng"];
                        if (!string.IsNullOrWhiteSpace(openid))
                        {
                            //发送消息
                            WebServiceShopping.wechartTools.SendMsg(new WebServiceShopping.wechartTools.ZhifuMsg()
                            {
                                miniprogram = new WebServiceShopping.wechartTools.XCXPath()
                                {
                                    pagepath = "/pages/my/store/store?ShopId=" + shopModel["shop_id"]
                                },
                                touser = openid,
                                data = new WebServiceShopping.wechartTools.ZhifuMsg.DataModel()
                                {
                                    keyword1 = new WebServiceShopping.wechartTools.DataItem()
                                    {
                                        value = name + "(" + phone + ")"
                                    },
                                    keyword2 = new WebServiceShopping.wechartTools.DataItem()
                                    {
                                        value = DateTime.Now.ToString("yyyy年MM月dd HH:mm")
                                    },
                                    keyword3 = new WebServiceShopping.wechartTools.DataItem()
                                    {
                                        value = "货到付款"
                                    },
                                    keyword4 = new WebServiceShopping.wechartTools.DataItem()
                                    {
                                        value = price.ToString("C") + "元"
                                    }
                                }
                            });
                        }
                    }
                    #endregion

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 根据订单号发货

        [WebMethod(Description = "根据订单号发货")]
        public string Shop_DeliverGoods(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_DeliverGoods) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"]; //发货人
                    var orderId = comrcv.Map_Args["OrderId"].ToLong(); //订单ID
                    var emstype = comrcv.Map_Args["EMS"].ToInt32(); //快递类型

                    var company = comrcv.Map_Args.ContainsKey("CompanyName") ? comrcv.Map_Args["CompanyName"] : string.Empty; //物流公司名
                    var account = comrcv.Map_Args.ContainsKey("CompanyAccount") ? comrcv.Map_Args["CompanyAccount"] : string.Empty; //物流公司账号

                    var emsnumber = comrcv.Map_Args.ContainsKey("EMSNumber") ? comrcv.Map_Args["EMSNumber"] : string.Empty; //快递单号
                    var emsname = comrcv.Map_Args.ContainsKey("EMSName") ? comrcv.Map_Args["EMSName"] : string.Empty; //快递名称
                    if (emstype == 0 && (string.IsNullOrWhiteSpace(company) || string.IsNullOrWhiteSpace(account)))
                    {
                        ret.Map_Args["ErrorMsg"] = "参数错误，自有物流必须有物流公司";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    //and order_status<2
                    var orderModel = mainsql.SqlExcuteWithReturn($"select * from {BIAOORDER} where order_id={orderId} and order_deleteflag=0 ").ToModels().FirstOrDefault();
                    if (orderModel == null)
                    {
                        ret.Map_Args["ErrorMsg"] = "订单错误或订单已被删除";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    var shopId = orderModel["shop_id"];
                    var paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@userid", userid));
                    paras.Add(new MySqlParameter("@ShopId", shopId));
                    var count = mainsql.SqlExecuteScalar($"select count(1) from {BIAOSHOPUSER} where user_id=@userid and shop_id=@ShopId and shop_user_deleteflag=0", paras.ToArray()).ToInt32();
                    if (count == 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "没有该店铺的操作权限";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    var shopModel = mainsql.SqlExcuteWithReturn($"select * from {BIAOSHOP} where shop_id='{shopId}'").ToModels().FirstOrDefault();
                    var fromuser = shopModel["shop_name"];
                    var fromaddress = shopModel["shop_address"];
                    var fromphone = shopModel["shop_tel_number"];

                    #region 自有物流发货
                    if (emstype == 0)
                    {
                        emsname = account;
                        double daishou = 0;
                        var isDaiShou = orderModel["order_pay_method"].ToInt32() != 0;
                        if (isDaiShou)
                        {
                            daishou = orderModel["order_price"].ToDouble() + orderModel["order_freight"].ToDouble();
                        }
                        var productModels = mainsql.SqlExcuteWithReturn($"select * from {BIAOORDERPRODUCT} where order_id={orderId}").ToModels();
                        var productNames = new List<string>();
                        var productNumber = 0;
                        foreach (var item in productModels)
                        {
                            var n = item["order_prd_number"].ToInt32();
                            productNames.Add(item["order_prd_name"] + "*" + n);
                            productNumber += n;
                        }
                        var phone = mainsql.SqlExecuteScalar($"select user_phone from {BIAOUSER} where user_onlyid='{orderModel["order_to_user_id"]}'")?.ToString();
                        var ems = new
                        {
                            funcId = "order.tmsadd",
                            companyaccount = account,  //物流公司账号
                            companyname = company,     //物流公司名称
                            longpos = shopModel["shop_longitude"], //发货人店铺坐标
                            latpos = shopModel["shop_latitude"],   //发货人店铺坐标
                            fahuorenaddress = shopModel["shop_address"],//发货人店铺地址
                            shipper = shopModel["shop_name"], //发货人店铺名称
                            shipperphone = fromphone,         //发货人店铺号码
                            phone = phone ?? orderModel["order_to_phone"],  //下单人号码
                            consignee = orderModel["order_to_user"], //收货人名称
                            consigneephone = orderModel["order_to_phone"], //收货人电话
                            consigneeads = orderModel["order_to_address"], //收货人地址
                            goodsname = string.Join(",", productNames),  //产品名称拼接数量
                            goodscount = productNumber,  //产品种类数量
                            collection = (isDaiShou ? daishou.ToDouble().ToString() : string.Empty) //代收金额
                        };
                        var poststr = JsonConvert.SerializeObject(ems);
                        loginfo.Info(poststr);
                        //emsnumber
                        var result = SmsSendInterface.postJson(_addOrderUrl, poststr);
                        loginfo.Info(result);
                        var json = Newtonsoft.Json.Linq.JToken.Parse(result);
                        if (json.Value<int>("code") == 1)
                        {
                            emsnumber = json.Value<string>("orderno");
                        }
                        else
                        {
                            ret.Map_Args["ErrorMsg"] = "发货失败";
                            mainsql.closesql();
                            goto EXIT;
                        }
                    }
                    #endregion

                    paras.Add(new MySqlParameter("@OrderId", orderId));
                    paras.Add(new MySqlParameter("@EMS", emstype));
                    paras.Add(new MySqlParameter("@EMSNumber", emsnumber));
                    paras.Add(new MySqlParameter("@EMSName", emsname));
                    paras.Add(new MySqlParameter("@FromUser", fromuser));
                    paras.Add(new MySqlParameter("@FromAddress", fromaddress));
                    paras.Add(new MySqlParameter("@FromPhone", fromphone));

                    mainsql.SqlExcuteNoReturn($"update {BIAOORDER} set order_status=2,order_to_time=NOW(),order_ems=@EMS,order_ems_number=@EMSNumber,order_ems_name=@EMSName,order_from_address=@FromAddress,order_from_phone=@FromPhone,order_from_user=@FromUser where order_id=@OrderId", paras.ToArray());

                    if (orderModel["order_pay_method"].ToInt32() == 2)
                    {
                        var paramMap = new Dictionary<string, object>();
                        paramMap.Add("notify_status", "1");
                        paramMap.Add("send_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        setOrderStatus(orderModel["order_number"], orderModel["order_ch_number"], paramMap);
                    }

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 查询可用的发货物流公司信息
        [WebMethod(Description = "查询可用的发货物流公司信息")]
        public string Shop_GetAllCompany(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetAllCompany) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                var lis = mainsql.SqlExcuteWithReturn($"select * from {BIAOCOMPANY} where com_isopen='0' or com_isopen is null order by com_index desc").ToModels();
                ret.Maplist_MapArgs.Add("Datas", lis);

                ret.Map_Args["ErrorMsg"] = "成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 根据订单号确认收货

        [WebMethod(Description = "根据订单号确认收货")]
        public string Shop_ConfirmGoods(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_ConfirmGoods) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "yonghusystem",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"]; //收货人
                    var orderId = comrcv.Map_Args["OrderId"].ToLong(); //订单ID

                    var orderModel = mainsql.SqlExcuteWithReturn($"select order_to_user_id,order_number,order_create_time,order_ch_number,shop_id,order_price,order_freight,order_pay_method,order_pay_status,order_pay_liushui  from {BIAOORDER} where order_id={orderId} and order_deleteflag=0 and order_status=2").ToModels().FirstOrDefault();
                    if (orderModel == null)
                    {
                        ret.Map_Args["ErrorMsg"] = "订单错误或订单未发货";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    var shopId = orderModel["shop_id"];
                    var payMethod = orderModel["order_pay_method"].ToInt32();
                    if (!(payMethod == 0 || payMethod == 2))//线上支付
                    {
                        ret.Map_Args["ErrorMsg"] = "订单错误";
                        mainsql.closesql();
                        goto EXIT;
                    }
                    var price = orderModel["order_price"].ToDouble() + orderModel["order_freight"].ToDouble();
                    var shopModel = mainsql.SqlExcuteWithReturn($"select shop_lock_balance,shop_rate,shop_ation,t2.c_account from {BIAOSHOP} t1 left join {BIAOCH} t2 on t1.shop_id=t2.shop_id where t1.shop_id='{shopId}'").ToModels().FirstOrDefault();
                    var lockPrice = shopModel["shop_lock_balance"].ToDouble();
                    var rate = shopModel["shop_rate"];
                    if (string.IsNullOrWhiteSpace(rate))
                    {
                        rate = mainsql.SqlExecuteScalar($"select c_name from s_config where c_type='shoprate'")?.ToString();
                    }
                    var fenchengrate = mainsql.SqlExecuteScalar($"select c_name from s_config where c_type='fenchengrate'")?.ToString();

                    //查询有没有特殊推广分成
                    var shopmodel = mainsql.SqlExcuteWithReturn($"select tg_yongjin,tg_tag,tg_rate from {BIAOUSER} t2 left join {BIAOUSERCOMPANY} t3 on t2.companyid=t3.user_id left join {BIAOSHOP} t4 on t3.user_tuiguangma=t4.shop_tuiguangma left join s_allshop t5 on t4.shop_id=t5.shop_id"
                        + " where t2.user_onlyid='" + userid + "'").ToModels().FirstOrDefault();
                    //查询店铺能不能适用特殊推广分成
                    if (!string.IsNullOrWhiteSpace(shopmodel["tg_tag"]))
                    {
                        var tags = shopModel["shop_ation"]?.ToString()?.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                        //店铺标签匹配上特殊推广标签
                        if (tags != null && tags.Length > 0 && tags.Contains(shopmodel["tg_tag"]))
                        {
                            //特殊费率
                            if (!string.IsNullOrWhiteSpace(shopmodel["tg_yongjin"]))
                                rate = shopmodel["tg_yongjin"];

                            if (!string.IsNullOrWhiteSpace(shopmodel["tg_rate"]))
                                fenchengrate = shopmodel["tg_rate"];
                        }
                    }
                    var shiji = price * rate.ToDouble();
                    var shiji2 = Math.Round(shiji, 2);
                    if (shiji2 < 0.01)
                        shiji2 = 0.01;
                    if (shiji2 < shiji)
                        shiji2 += 0.01;
                    if (shiji2 >= price)
                    {
                        shiji2 = 0;
                    }
                    shiji = Math.Round(shiji2, 2);
                    var shopprice = price - shiji;
                    shopprice = Math.Round(shopprice, 2);

                    var qgliushui = orderModel["order_pay_liushui"];
                    var shopAccount = shopModel["c_account"];
                    if (!string.IsNullOrWhiteSpace(qgliushui) && !string.IsNullOrWhiteSpace(shopAccount))
                    {
                        Dictionary<string, string> mapargs = new Dictionary<string, string>();
                        mapargs.Add("qgliushuinumber", qgliushui);
                        var chaccount = mainsql.SqlExecuteScalar("select c_account from s_shopchuanhua where c_id='10000000000'")?.ToString();
                        //店铺账号8800012802019，店铺收入；官方账号，官方收入
                        var str = $"{shopAccount},{shopprice};{chaccount},{shiji}";
                        loginfo.Info(str);
                        mapargs.Add("shareinfo", str);

                        if (!CH_ZHIFU_Share(ref mapargs))
                        {
                            mainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "请求分账传化服务器异常";
                            goto EXIT;
                        }
                        //修改店铺订单数
                        mainsql.SqlExcuteNoReturn($"update {BIAOSHOP} set shop_order_number=shop_order_number+1,shop_good_number=shop_good_number+1 where shop_id='{shopId}'");
                    }
                    else if (payMethod == 2)
                    {
                        mainsql.SqlExcuteNoReturn($"update {BIAOSHOP} set shop_order_number=shop_order_number+1,shop_good_number=shop_good_number+1 where shop_id='{shopId}'");

                        var paramMap = new Dictionary<string, object>();
                        paramMap.Add("notify_status", "2");
                        paramMap.Add("receive_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        setOrderStatus(orderModel["order_number"], orderModel["order_ch_number"], paramMap);
                    }
                    else
                    {
                        if (lockPrice < shopprice)
                        {
                            loginfo.Info($"店铺金额异常，shop_id：{shopId} 订单号：{orderId} 订单金额：{shopprice} 店铺锁定金额：{lockPrice}");
                            shopprice = lockPrice;
                        }
                        //修改店铺余额，修改订单数
                        mainsql.SqlExcuteNoReturn($"update {BIAOSHOP} set shop_lock_balance=shop_lock_balance-{shopprice.ToString("0.00")},shop_balance=shop_balance+{shopprice.ToString("0.00")},shop_order_number=shop_order_number+1,shop_good_number=shop_good_number+1 where shop_id='{shopId}'");

                        #region 店铺分成
                        var fenchengShopModel = mainsql.SqlExcuteWithReturn($"select t3.*,user_phone,companyid from {BIAOUSER} t1 inner join {BIAOUSERCOMPANY} t2 on t1.companyid=t2.user_id left join {BIAOSHOP} t3 on t2.user_tuiguangma=t3.shop_tuiguangma where t1.user_onlyid='{orderModel["order_to_user_id"]}' and (user_tuiguangma is not null and user_tuiguangma<>'') and t3.shop_id is not null").ToModels().FirstOrDefault();

                        if (fenchengShopModel != null && fenchengrate.ToDouble() > 0)
                        {
                            var zhifuconfig = mainsql.SqlExcuteWithReturn(string.Format("SELECT * from {0} where com_account='qingguan' AND com_number='00000' ;", BIAOQGZHIFUCOMPANY)).ToModels().FirstOrDefault();
                            if (zhifuconfig == null)
                            {
                                ret.Map_Args["ErrorMsg"] = "没有开通支付功能";
                                mainsql.closesql();
                                goto EXIT;
                            }

                            var fencheng = (price - shopprice) * fenchengrate.ToDouble();

                            var defaultstr = string.Format("店铺分成{0}元，分成费率{1}", fencheng.ToString("0.00"), fenchengrate);

                            var qgliushuinumber = GetCompanyDDNumber(mainsql, zhifuconfig["com_numberdate"], "qingguan");
                            //生成青贯流水号
                            qgliushuinumber = zhifuconfig["com_number"] + DateTime.Now.ToString("yyyyMMddHHmmss") + qgliushuinumber;
                            var sqlcmd = string.Format("INSERT INTO {0} (zf_time,zf_type,zf_status,zf_qgnumber,zf_chnumber,zf_biaoid,zf_companyaccount," +
                                  "zf_companynumber,zf_companyname,zf_yhamount,zf_yholdamount,zf_qgamount,zf_companyamount,zf_default,zf_zfphone,zf_way,zf_shouzhi,zf_comshouzhi,zf_zfonlyid,zf_companyrealtimebalance)" +
                                  " VALUES ('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','系统','2','1','{16}','{17}')",
                                 BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "推广分成", "支付成功", qgliushuinumber,
                                 string.Empty, orderModel["order_number"], fenchengShopModel["shop_id"], string.Empty, fenchengShopModel["shop_name"],
                                 price.ToString("0.00"), price, 0.ToString("0.00"), fencheng.ToString("0.00"), defaultstr, fenchengShopModel["user_phone"]?.ToString() ?? string.Empty, string.Empty, (fenchengShopModel["shop_balance"].ToDouble() + fencheng).ToString("0.00"));
                            var sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                            if (sqlret != 1)
                            {
                                mainsql.closesql();
                                ret.Map_Args["ErrorMsg"] = "插入分成账单记录失败";
                                goto EXIT;
                            }

                            if (mainsql.SqlExcuteNoReturn($"update {BIAOSHOP} set shop_balance=shop_balance+{fencheng.ToString("0.00")} where shop_id='{fenchengShopModel["shop_id"]}'") != 1)
                            {
                                mainsql.closesql();
                                ret.Map_Args["ErrorMsg"] = "设置店铺分成金额失败";
                                goto EXIT;
                            }

                            if (mainsql.SqlExcuteNoReturn($"insert into {BIAOORDERFENCHENG} values('{orderId}','{orderModel["order_number"]}','{orderModel["order_create_time"]}','{price.ToString("0.00")}','{fencheng.ToString("0.00")}','{fenchengrate}','{orderModel["order_to_user_id"]}','{fenchengShopModel["companyid"]}','{fenchengShopModel["shop_id"]}')") != 1)
                            {
                                mainsql.closesql();
                                ret.Map_Args["ErrorMsg"] = "插入分成记录失败";
                                goto EXIT;
                            }

                        }
                        #endregion
                    }
                    //修改订单状态、付款状态
                    mainsql.SqlExcuteNoReturn($"update {BIAOORDER} set order_status=3,order_pay_status=2,order_pay_method=0,order_confirm_time=NOW() where order_id={orderId}");

                    //修改产品销售数量
                    mainsql.SqlExcuteNoReturn($"update {BIAOPRODUCT} t1,{BIAOORDERPRODUCT} t2 set t1.prd_sale_number=t1.prd_sale_number+t2.order_prd_number where t1.prd_id=t2.prd_id and t2.order_id={orderId}");


                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 代付确认收货

        [WebMethod(Description = "代付确认收货")]
        public string Shop_ConfirmGoodsDaiFu(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_ConfirmGoodsDaiFu) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                var orderIds = comrcv.Map_Args["OrderIds"].Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries); //订单ID

                var zhifuconfig = mainsql.SqlExcuteWithReturn(string.Format("SELECT * from {0} where com_account='qingguan' AND com_number='00000' ;", BIAOQGZHIFUCOMPANY)).ToModels().FirstOrDefault();
                if (zhifuconfig == null)
                {
                    ret.Map_Args["ErrorMsg"] = "没有开通支付功能";
                    mainsql.closesql();
                    goto EXIT;
                }
                foreach (var orderId in orderIds)
                {
                    using (TransactionScope tsall = new TransactionScope())
                    {
                        var orderModel = mainsql.SqlExcuteWithReturn($"select shop_id,order_create_time,order_to_user_id,order_number,order_price,order_freight,order_pay_method,order_pay_status,order_ems_name,order_ems_number2  from {BIAOORDER} where order_id={orderId} and order_deleteflag=0 and order_status=2").ToModels().FirstOrDefault();
                        if (orderModel == null)
                        {
                            ret.Map_Args.Add(orderId, "订单错误或订单未发货");
                            continue;
                        }
                        var touserid = orderModel["order_to_user_id"];
                        var shopId = orderModel["shop_id"];
                        if (orderModel["order_pay_method"].ToInt32() != 1)//货到付款
                        {
                            ret.Map_Args.Add(orderId, "订单错误");
                            continue;
                        }

                        var shopModel = mainsql.SqlExcuteWithReturn($"select * from {BIAOSHOP} where shop_id='{shopId}'").ToModels().FirstOrDefault();
                        if (shopModel == null)
                        {
                            ret.Map_Args.Add(orderId, "订单相关店铺不存在");
                            continue;
                        }
                        var price = orderModel["order_price"].ToDouble();
                        var account = orderModel["order_ems_name"];
                        var companyModel = mainsql.SqlExcuteWithReturn($"select * from {BIAOCOMPANY} where com_account='{account}'").ToModels().FirstOrDefault();
                        if (companyModel == null)
                        {
                            ret.Map_Args.Add(orderId, "订单相关物流公司不存在");
                            continue;
                        }
                        var companyPrice = companyModel["com_price"].ToDouble();
                        if (companyPrice < price)
                        {
                            ret.Map_Args.Add(orderId, "物流公司余额不足");
                            continue;
                        }

                        var comfeilvstr = shopModel["shop_rate"];
                        if (string.IsNullOrWhiteSpace(comfeilvstr))
                        {
                            comfeilvstr = mainsql.SqlExecuteScalar($"select c_name from s_config where c_type='shoprate'")?.ToString();
                        }

                        var fenchengrate = mainsql.SqlExecuteScalar($"select c_name from s_config where c_type='fenchengrate'")?.ToString();

                        //查询有没有特殊推广分成
                        var shopmodel = mainsql.SqlExcuteWithReturn($"select tg_yongjin,tg_tag,tg_rate from {BIAOUSER} t2 left join {BIAOUSERCOMPANY} t3 on t2.companyid=t3.user_id left join {BIAOSHOP} t4 on t3.user_tuiguangma=t4.shop_tuiguangma left join s_allshop t5 on t4.shop_id=t5.shop_id"
                            + " where t2.user_onlyid='" + touserid + "'").ToModels().FirstOrDefault();
                        //查询店铺能不能适用特殊推广分成
                        if (!string.IsNullOrWhiteSpace(shopmodel["tg_tag"]))
                        {
                            var tags = shopModel["shop_ation"]?.ToString()?.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                            //店铺标签匹配上特殊推广标签
                            if (tags != null && tags.Length > 0 && tags.Contains(shopmodel["tg_tag"]))
                            {
                                //特殊费率
                                if (!string.IsNullOrWhiteSpace(shopmodel["tg_yongjin"]))
                                    comfeilvstr = shopmodel["tg_yongjin"];

                                if (!string.IsNullOrWhiteSpace(shopmodel["tg_rate"]))
                                    fenchengrate = shopmodel["tg_rate"];
                            }
                        }

                        #region 计算分账金额
                        double shopprice = 0;   //公司得到的金额
                        {
                            //计算相关金额
                            double yonghujine = price;   //支付的金额

                            double comfeilvdb = 0;   //青贯跟公司费率


                            double.TryParse(comfeilvstr, out comfeilvdb);


                            if (yonghujine == 0)
                            {
                                ret.Map_Args["ErrorMsg"] = "金额错误";  //参数错误
                                goto EXIT;
                            }
                            double companyjineshouxu = yonghujine * comfeilvdb;
                            shopprice = yonghujine;
                            if (comfeilvdb > 0)
                            {
                                var companyjineshouxu2 = Math.Round(companyjineshouxu, 2);//将手续费变成两位小数
                                if (companyjineshouxu2 < 0.01)
                                    companyjineshouxu2 = 0.01;
                                if (companyjineshouxu2 < companyjineshouxu)
                                    companyjineshouxu2 += 0.01;
                                if (yonghujine <= companyjineshouxu2)
                                {
                                    companyjineshouxu2 = 0;
                                }
                                companyjineshouxu = Math.Round(companyjineshouxu2, 2);

                                shopprice = yonghujine - companyjineshouxu;
                                shopprice = Math.Round(shopprice, 2);
                            }
                        }
                        double comprice = 0;//物流公司扣除的金额
                        {
                            //计算相关金额
                            double yonghujine = price;   //支付的金额
                            double comfeilvdb = 0;   //青贯跟公司费率

                            double.TryParse(companyModel["com_rate"], out comfeilvdb);


                            if (yonghujine == 0)
                            {
                                ret.Map_Args["ErrorMsg"] = "金额错误";  //参数错误
                                goto EXIT;
                            }
                            double companyjineshouxu = yonghujine * comfeilvdb;
                            comprice = yonghujine;
                            if (comfeilvdb > 0)
                            {
                                var companyjineshouxu2 = Math.Round(companyjineshouxu, 2);//将手续费变成两位小数
                                if (companyjineshouxu2 < 0.01)
                                    companyjineshouxu2 = 0.01;
                                if (companyjineshouxu2 < companyjineshouxu)
                                    companyjineshouxu2 += 0.01;
                                if (yonghujine <= companyjineshouxu2)
                                {
                                    companyjineshouxu2 = 0;
                                }
                                companyjineshouxu = Math.Round(companyjineshouxu2, 2);

                                comprice = yonghujine - companyjineshouxu;
                                comprice = Math.Round(comprice, 2);
                            }
                        }
                        #endregion

                        #region 生成账单记录表

                        string defaultstr = string.Format("用户支付{0}元,实际到账{1}元", price, shopprice.ToString("0.00"));

                        var qgliushuinumber = GetCompanyDDNumber(mainsql, zhifuconfig["com_numberdate"], "qingguan");
                        //生成青贯流水号
                        qgliushuinumber = zhifuconfig["com_number"] + DateTime.Now.ToString("yyyyMMddHHmmss") + qgliushuinumber;

                        string sqlcmd = string.Format("INSERT INTO {0} (zf_time,zf_type,zf_status,zf_qgnumber,zf_chnumber,zf_biaoid,zf_companyaccount," +
                            "zf_companynumber,zf_companyname,zf_yhamount,zf_yholdamount,zf_qgamount,zf_companyamount,zf_default,zf_zfphone,zf_way,zf_shouzhi,zf_comshouzhi,zf_zfonlyid)" +
                            " VALUES ('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','代收货款','2','1','{16}')",
                           BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "商品支付", "支付成功", qgliushuinumber,
                           string.Empty, orderModel["order_number"], shopId, string.Empty, shopModel["shop_name"],
                           price.ToString("0.00"), price, 0.ToString("0.00"), shopprice.ToString("0.00"), defaultstr, string.Empty, account);
                        int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            ret.Map_Args.Add(orderId, "插入记录失败");
                            continue;
                        }

                        #endregion

                        #region 店铺分成
                        var fenchengShopModel = mainsql.SqlExcuteWithReturn($"select t3.*,t1.user_phone,companyid from {BIAOUSER} t1 inner join {BIAOUSERCOMPANY} t2 on t1.companyid=t2.user_id left join {BIAOSHOP} t3 on t2.user_tuiguangma=t3.shop_tuiguangma where t1.user_onlyid='{touserid}' and (user_tuiguangma is not null and user_tuiguangma<>'') and t3.shop_id is not null ").ToModels().FirstOrDefault();
                        if (fenchengShopModel != null && fenchengrate.ToDouble() > 0)
                        {
                            var fencheng = (price - shopprice) * fenchengrate.ToDouble();

                            defaultstr = string.Format("店铺分成{0}元，分成费率{1}", fencheng.ToString("0.00"), fenchengrate);

                            qgliushuinumber = GetCompanyDDNumber(mainsql, zhifuconfig["com_numberdate"], "qingguan");
                            //生成青贯流水号
                            qgliushuinumber = zhifuconfig["com_number"] + DateTime.Now.ToString("yyyyMMddHHmmss") + qgliushuinumber;
                            sqlcmd = string.Format("INSERT INTO {0} (zf_time,zf_type,zf_status,zf_qgnumber,zf_chnumber,zf_biaoid,zf_companyaccount," +
                                "zf_companynumber,zf_companyname,zf_yhamount,zf_yholdamount,zf_qgamount,zf_companyamount,zf_default,zf_zfphone,zf_way,zf_shouzhi,zf_comshouzhi,zf_zfonlyid,zf_companyrealtimebalance)" +
                                " VALUES ('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','系统','2','1','','{16}')",
                               BIAOQGZHIFURECORD + DateTime.Now.ToString("yyyyMM"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "推广分成", "支付成功", qgliushuinumber,
                               string.Empty, orderModel["order_number"], fenchengShopModel["shop_id"], string.Empty, fenchengShopModel["shop_name"],
                               price.ToString("0.00"), price, 0.ToString("0.00"), fencheng.ToString("0.00"), defaultstr, fenchengShopModel["user_phone"]?.ToString() ?? string.Empty, (fenchengShopModel["shop_balance"].ToDouble() + fencheng).ToString("0.00"));
                            sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                            if (sqlret != 1)
                            {
                                ret.Map_Args.Add(orderId, "插入分成记录失败");
                                continue;
                            }
                            if (mainsql.SqlExcuteNoReturn($"update {BIAOSHOP} set shop_balance=shop_balance+{fencheng.ToString("0.00")} where shop_id='{fenchengShopModel["shop_id"]}'") != 1)
                            {
                                ret.Map_Args.Add(orderId, "设置店铺分成金额失败");
                                continue;
                            }
                            if (mainsql.SqlExcuteNoReturn($"insert into {BIAOORDERFENCHENG} values('{orderId}','{orderModel["order_number"]}','{orderModel["order_create_time"]}','{price.ToString("0.00")}','{fencheng.ToString("0.00")}','{fenchengrate}','{orderModel["order_to_user_id"]}','{fenchengShopModel["companyid"]}','{fenchengShopModel["shop_id"]}')") != 1)
                            {
                                ret.Map_Args.Add(orderId, "插入分成记录失败");
                                continue;
                            }
                        }
                        #endregion

                        //修改店铺余额，修改订单数
                        mainsql.SqlExcuteNoReturn($"update {BIAOSHOP} set shop_order_number=shop_order_number+1,shop_good_number=shop_good_number+1,shop_balance=shop_balance+{shopprice.ToString("0.00")} where shop_id='{shopId}'");
                        //修改物流余额
                        mainsql.SqlExcuteNoReturn($"update {BIAOCOMPANY} set com_price={(companyModel["com_price"].ToDouble() - comprice).ToString("0.00")} where com_account='{account}'");
                        //增加日志
                        mainsql.SqlExcuteNoReturn($"insert into {BIAOCOMPANYR}(com_name,com_account,com_r_price,com_price,com_r_break,com_r_time)"
                            + $"values('{companyModel["com_name"]}','{companyModel["com_account"]}',{price},{(companyModel["com_price"].ToDouble() - comprice).ToString("0.00")},'订单{orderModel["order_ems_number2"]}扣款{comprice.ToString("0.00")}',NOW())");
                        //修改订单状态、付款状态
                        mainsql.SqlExcuteNoReturn($"update {BIAOORDER} set order_status=3,order_pay_status=2,order_confirm_time=NOW() where order_id={orderId}");
                        //修改产品销售数量
                        mainsql.SqlExcuteNoReturn($"update {BIAOPRODUCT} t1,{BIAOORDERPRODUCT} t2 set t1.prd_sale_number=t1.prd_sale_number+t2.order_prd_number where t1.prd_id=t2.prd_id and t2.order_id={orderId}");


                        #region 修改运单状态
#if DEBUG
                        if (false)
#endif
                        {
                            var ems = new
                            {
                                funcId = "order.daishoufukuan",
                                companyaccount = account,  //物流公司账号
                                orderno = orderModel["order_ems_number2"], //运单号
                                shouxufeilv = companyModel["com_rate"]
                            };
                            var poststr = JsonConvert.SerializeObject(ems);
                            loginfo.Info(poststr);
                            var result = SmsSendInterface.postJson(_addOrderUrl, poststr);
                            loginfo.Info(result);
                            var json = Newtonsoft.Json.Linq.JToken.Parse(result);
                            if (json.Value<int>("code") == 1)
                            {
                            }
                            else
                            {
                                ret.Map_Args.Add(orderId, "运单物流数据错误");
                                continue;
                            }
                        }
                        #endregion

                        tsall.Complete();
                    }
                }

                ret.Map_Args["ErrorMsg"] = "操作成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 根据订单号评价订单

        [WebMethod(Description = "根据订单号评价订单")]
        public string Shop_ScoreOrder(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_ScoreOrder) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"]; //收货人
                    var orderId = comrcv.Map_Args["OrderId"].ToLong(); //订单ID
                    var score = comrcv.Map_Args["Score"].ToInt32(); //评分 0好评1差评
                    var pId = comrcv.Map_Args.ContainsKey("ID") ? comrcv.Map_Args["ID"].ToLong() : 0;//如果是追评，上一条评价的ID
                    var descript = comrcv.Map_Args.ContainsKey("Content") ? comrcv.Map_Args["Content"] : string.Empty; //评价内容
                    var fileIds = comrcv.Map_Args["files"];
                    var tagName = comrcv.Map_Args.ContainsKey("Tag") ? comrcv.Map_Args["Tag"] : string.Empty;

                    var shopId = mainsql.SqlExecuteScalar($"select shop_id from {BIAOORDER} where order_id={orderId} and order_to_user_id='{userid}' and order_deleteflag=0 and order_status=3")?.ToString();
                    if (string.IsNullOrWhiteSpace(shopId))
                    {
                        ret.Map_Args["ErrorMsg"] = "订单错误或订单未确认收货";
                        mainsql.closesql();
                        goto EXIT;
                    }

                    if (!string.IsNullOrWhiteSpace(tagName))
                    {
                        mainsql.SqlExcuteNoReturn(string.Format("insert into {0}(shop_id,tag_name,tag_create_time,tag_create_user,tag_deleteflag)values"
                            + "(@ShopId,@Name,NOW(),@userid,0)", BIAOSHOPTAGS), new MySqlParameter("@ShopId", shopId), new MySqlParameter("@Name", tagName), new MySqlParameter("@userid", userid));
                    }

                    if (!string.IsNullOrWhiteSpace(descript) && !string.IsNullOrWhiteSpace(fileIds))
                    {//添加订单备注
                        ConvertTemporary(mainsql, fileIds);
                        var paras = new List<MySqlParameter>();
                        paras.Add(new MySqlParameter("@OrderId", orderId));
                        paras.Add(new MySqlParameter("@userid", userid));
                        paras.Add(new MySqlParameter("@Content", descript));
                        paras.Add(new MySqlParameter("@files", fileIds));
                        if (pId > 0)
                            paras.Add(new MySqlParameter("@ParentId", pId));
                        else paras.Add(new MySqlParameter("@ParentId", MySqlDbType.Int64) { Value = DBNull.Value });

                        mainsql.SqlExcuteNoReturn($"insert into {BIAOORDERADD}(order_id,order_add_create_time,order_add_create_user,order_add_type,order_add_parent_id,order_add_content,order_add_file_ids)values(@OrderId,NOW(),@userid,1,@ParentId,@Content,@files)", paras.ToArray());
                    }
                    mainsql.SqlExcuteNoReturn($"update {BIAOORDER} set order_score={score},order_score_time=NOW() where order_id={orderId}");
                    if (score == 1)
                    {
                        mainsql.SqlExcuteNoReturn($"update {BIAOSHOP} set shop_good_number=shop_good_number-1 where shop_id='{shopId}'");
                    }
                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 售后申请列表分页查询(买家)

        [WebMethod(Description = "售后申请列表分页查询(买家)")]
        public string Shop_OrderSaleByPageBuyer(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_OrderSaleByPageBuyer) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                var pageIndex = comrcv.Map_Args["pageIndex"].ToInt32();
                pageIndex = pageIndex == 0 ? 1 : pageIndex;
                var pageSize = comrcv.Map_Args["pageSize"].ToInt32();
                pageSize = pageSize == 0 ? 10 : pageSize;

                var userId = comrcv.Map_Args.ContainsKey("userid") ? comrcv.Map_Args["userid"] : string.Empty;
                if (string.IsNullOrWhiteSpace(userId))
                {
                    ret.Map_Args["ErrorMsg"] = "参数异常";
                    mainsql.closesql();
                    goto EXIT;
                }

                StringBuilder sql = new StringBuilder();
                sql.AppendFormat("select t1.*,t2.shop_name as ShopName,t3.file_small_path as ShopTitlePath from {0} t1 "
                    + "left join (select order_id from {3} where sa_status<>1 group by order_id) as t4 on t1.order_id=t4.order_id "
                    + "left join {1} t2 on t1.shop_id=t2.shop_id "
                    + "left join {2} t3 on t2.shop_title_id=t3.file_id where t1.order_deleteflag=0 and t1.order_status=3 and t4.order_id is null ", BIAOORDER, BIAOSHOP, BIAOSHOPFILE, BIAOORDERSALE);

                if (!string.IsNullOrWhiteSpace(userId))
                {
                    sql.AppendFormat(" and order_to_user_id='{0}'", userId);
                }

                string sqlStr = $"select t1.*,t3.file_small_path as ProductTitlePath from {BIAOORDERPRODUCT} t1 left join ({sql.ToString()}) t2 on t1.order_id=t2.order_id left join {BIAOSHOPFILE} t3 on t1.order_prd_cover_id=t3.file_id where t2.order_id>0";
                sql.AppendFormat(" order by order_create_time desc limit {0},{1}", pageSize * pageIndex - pageSize, pageSize);

                var models = mainsql.SqlExcuteWithReturn(sql.ToString()).ToModels();

                if (models.Count > 0)
                {
                    ret.Maplist_MapArgs.Add("Products", mainsql.SqlExcuteWithReturn(sqlStr).ToModels());
                }

                ret.Maplist_MapArgs.Add("Order", models);
                ret.Map_Args["ErrorMsg"] = "成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }


        #endregion

        #region 售后记录分页查询

        [WebMethod(Description = "售后记录分页查询")]
        public string Shop_OrderSaleByPage(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_OrderSaleByPage) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                var pageIndex = comrcv.Map_Args["pageIndex"].ToInt32();
                pageIndex = pageIndex == 0 ? 1 : pageIndex;
                var pageSize = comrcv.Map_Args["pageSize"].ToInt32();
                pageSize = pageSize == 0 ? 10 : pageSize;

                //卖家传店铺，不传用户ID。 买家传用户ID，不传店铺ID
                var userId = comrcv.Map_Args.ContainsKey("userid") ? comrcv.Map_Args["userid"] : string.Empty;
                var shopId = comrcv.Map_Args.ContainsKey("ShopId") ? comrcv.Map_Args["ShopId"] : string.Empty;
                if (string.IsNullOrWhiteSpace(userId) && string.IsNullOrWhiteSpace(shopId))
                {
                    ret.Map_Args["ErrorMsg"] = "参数异常";
                    mainsql.closesql();
                    goto EXIT;
                }

                StringBuilder sql = new StringBuilder();
                sql.AppendFormat("select t1.*,t2.shop_name as ShopName,t3.file_small_path as ShopTitlePath,t4.sa_id,t4.sa_createtime,t4.sa_type,t4.sa_content,t4.sa_status from {0} t1 "
                    + "inner join {3} t4 on t1.order_id=t4.order_id "
                    + "left join {1} t2 on t1.shop_id=t2.shop_id "
                    + "left join {2} t3 on t2.shop_title_id=t3.file_id where t1.order_deleteflag=0", BIAOORDER, BIAOSHOP, BIAOSHOPFILE, BIAOORDERSALE);

                if (!string.IsNullOrWhiteSpace(userId))
                {
                    sql.AppendFormat(" and order_to_user_id='{0}'", userId);
                }
                if (!string.IsNullOrWhiteSpace(shopId))
                {
                    sql.AppendFormat(" and t1.shop_id='{0}'", shopId);
                }

                if (comrcv.Map_Args.ContainsKey("Status"))
                {
                    //售后状态：0：正常，1：结束
                    var status = comrcv.Map_Args["Status"].ToInt32();
                    if (status == 0)
                        sql.Append(" and (t4.sa_status=0 or t4.sa_status=2)");
                    else
                    {
                        sql.Append(" and t4.sa_status=" + status);
                    }
                }

                string sqlStr = $"select t1.*,t3.file_small_path as ProductTitlePath from {BIAOORDERPRODUCT} t1 left join ({sql.ToString()}) t2 on t1.order_id=t2.order_id left join {BIAOSHOPFILE} t3 on t1.order_prd_cover_id=t3.file_id where t2.order_id>0";
                sql.AppendFormat(" order by sa_status asc,sa_createtime desc limit {0},{1}", pageSize * pageIndex - pageSize, pageSize);

                var models = mainsql.SqlExcuteWithReturn(sql.ToString()).ToModels();

                if (models.Count > 0)
                {
                    ret.Maplist_MapArgs.Add("Products", mainsql.SqlExcuteWithReturn(sqlStr).ToModels());
                    foreach (var item in models)
                    {
                        if (item.ContainsKey("sa_content") && !string.IsNullOrWhiteSpace(item["sa_content"]))
                        {
                            try
                            {
                                item["sa_content"] = Encoding.UTF8.GetString(Convert.FromBase64String(item["sa_content"]));
                            }
                            catch
                            { }
                        }
                    }
                }

                ret.Maplist_MapArgs.Add("Order", models);
                ret.Map_Args["ErrorMsg"] = "成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 售后记录详情查询
        [WebMethod(Description = "售后记录详情查询")]
        public string Shop_OrderSaleDetail(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_OrderSaleByPage) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                var said = comrcv.Map_Args["sa_id"];

                var models = mainsql.SqlExcuteWithReturn($"select * from {BIAOORDERSALE} where sa_id='{said}'").ToModels();
                var datas = mainsql.SqlExcuteWithReturn($"select *,t2.user_name,t2.user_phone from {BIAOORDERSALEADD} t1 left join {BIAOUSER} t2 on t1.sa_add_create_user=t2.user_onlyid WHERE sa_id='{said}' order by sa_add_index").ToModels();

                var ids = string.Empty;
                datas.ForEach(x =>
                {
                    if (x.ContainsKey("sa_add_file_ids"))
                        ids += ("," + x["sa_add_file_ids"]);
                    if (x.ContainsKey("sa_add_content") && !string.IsNullOrWhiteSpace(x["sa_add_content"]))
                        try
                        {
                            x["sa_add_content"] = Encoding.UTF8.GetString(Convert.FromBase64String(x["sa_add_content"]));
                        }
                        catch
                        { }
                });
                if (models.FirstOrDefault() != null)
                {
                    if (models[0].ContainsKey("sa_content") && !string.IsNullOrWhiteSpace(models[0]["sa_content"]))
                    {
                        try
                        {
                            models[0]["sa_content"] = Encoding.UTF8.GetString(Convert.FromBase64String(models[0]["sa_content"]));
                        }
                        catch
                        { }
                    }
                }
                var idlist = ids.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                if (idlist.Length > 0)
                {
                    var files = mainsql.SqlExcuteWithReturn($"select file_id,file_path from s_files where file_id in('{string.Join("','", idlist)}')").ToModels();
                    ret.Maplist_MapArgs.Add("Files", files);//图片
                }

                ret.Maplist_MapArgs.Add("Model", models);  //售后记录 一条
                ret.Maplist_MapArgs.Add("Datas", datas);   //售后信息 多条，有买家、卖家、客服的发言信息
                ret.Map_Args["ErrorMsg"] = "成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 买家申请售后

        [WebMethod(Description = "买家申请售后")]
        public string Shop_OrderSaleAdd(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_OrderSaleAdd) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                var userid = comrcv.Map_Args["userid"]; //用户ID
                var orderid = comrcv.Map_Args["OrderId"]; //订单ID

                var type = comrcv.Map_Args["type"]; //0：退，1：换，2：修
                var content = comrcv.Map_Args["Content"]; //内容
                if (!string.IsNullOrWhiteSpace(content)) content = Convert.ToBase64String(Encoding.UTF8.GetBytes(content));
                var fileIds = comrcv.Map_Args["files"]; //图片

                if (string.IsNullOrWhiteSpace(userid))
                {
                    ret.Map_Args["ErrorMsg"] = "参数异常";
                    mainsql.closesql();
                    goto EXIT;
                }
                var paras = new List<MySqlParameter>();
                paras.Add(new MySqlParameter("@orderid", orderid));
                paras.Add(new MySqlParameter("@userid", userid));
                paras.Add(new MySqlParameter("@type", type));
                paras.Add(new MySqlParameter("@content", content));
                paras.Add(new MySqlParameter("@fileids", fileIds));

                var said = mainsql.SqlExecuteScalar($"insert into {BIAOORDERSALE}(order_id,sa_createtime,sa_createuser,sa_type,sa_content,sa_status)"
                    + "values(@orderid,NOW(),@userid,@type,@content,0);SELECT @@IDENTITY", paras.ToArray()).ToLong();
                if (said == 0)
                {
                    ret.Map_Args["ErrorMsg"] = "数据插入失败";
                    mainsql.closesql();
                    goto EXIT;
                }

                paras.Add(new MySqlParameter("@said", said));
                if (mainsql.SqlExcuteNoReturn($"insert into {BIAOORDERSALEADD}(sa_id,sa_add_create_time,sa_add_create_user,sa_add_type,sa_add_content,sa_add_file_ids,sa_add_index)"
                     + "values(@said,NOW(),@userid,0,@content,@fileids,1)", paras.ToArray()) == -1)
                {
                    ret.Map_Args["ErrorMsg"] = "数据插入失败";
                    mainsql.closesql();
                    goto EXIT;
                }

                //如果有附件图片，转成永久
                if (!string.IsNullOrWhiteSpace(fileIds))
                    ConvertTemporary(mainsql, fileIds);

                ret.Map_Args["ErrorMsg"] = "成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 买家处理售后

        [WebMethod(Description = "买家处理售后")]
        public string Shop_OrderSaleBuyer(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_OrderSaleBuyer) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                var userid = comrcv.Map_Args["userid"]; //用户ID
                var said = comrcv.Map_Args["sa_id"]; //售后id

                var type = comrcv.Map_Args["type"]; //0正常，3评价
                var content = comrcv.Map_Args["Content"];
                if (!string.IsNullOrWhiteSpace(content)) content = Convert.ToBase64String(Encoding.UTF8.GetBytes(content));
                var fileIds = comrcv.Map_Args["files"];

                if (string.IsNullOrWhiteSpace(userid) || string.IsNullOrWhiteSpace(said))
                {
                    ret.Map_Args["ErrorMsg"] = "参数异常";
                    mainsql.closesql();
                    goto EXIT;
                }


                var paras = new List<MySqlParameter>();
                paras.Add(new MySqlParameter("@userid", userid));
                paras.Add(new MySqlParameter("@type", type));
                paras.Add(new MySqlParameter("@content", content));
                paras.Add(new MySqlParameter("@fileids", fileIds));
                paras.Add(new MySqlParameter("@said", said));

                var maxindex = mainsql.SqlExecuteScalar($"select sa_add_index from {BIAOORDERSALEADD} where sa_id='{said}'").ToInt32();
                paras.Add(new MySqlParameter("@max", maxindex + 1));
                if (mainsql.SqlExcuteNoReturn($"insert into {BIAOORDERSALEADD}(sa_id,sa_add_create_time,sa_add_create_user,sa_add_type,sa_add_content,sa_add_file_ids,sa_add_index)"
                     + "values(@said,NOW(),@userid,@type,@content,@fileids,@max)", paras.ToArray()) == -1)
                {
                    ret.Map_Args["ErrorMsg"] = "数据插入失败";
                    mainsql.closesql();
                    goto EXIT;
                }

                //如果有附件图片，转成永久
                if (!string.IsNullOrWhiteSpace(fileIds))
                    ConvertTemporary(mainsql, fileIds);


                ret.Map_Args["ErrorMsg"] = "成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 卖家处理售后

        [WebMethod(Description = "卖家处理售后")]
        public string Shop_OrderSaleShop(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_OrderSaleShop) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                var userid = comrcv.Map_Args["userid"]; //当前用户ID，店铺回复人
                var shopid = comrcv.Map_Args["ShopId"]; //店铺ID
                var said = comrcv.Map_Args["sa_id"]; //售后id

                var type = comrcv.Map_Args["type"]; //1正常，4评价
                var content = comrcv.Map_Args["Content"];
                if (!string.IsNullOrWhiteSpace(content)) content = Convert.ToBase64String(Encoding.UTF8.GetBytes(content));
                var fileIds = comrcv.Map_Args["files"];
                var status = comrcv.Map_Args["status"].ToInt32(); //0正常，1结束售后

                if (string.IsNullOrWhiteSpace(userid) || string.IsNullOrWhiteSpace(said))
                {
                    ret.Map_Args["ErrorMsg"] = "参数异常";
                    mainsql.closesql();
                    goto EXIT;
                }


                var paras = new List<MySqlParameter>();
                paras.Add(new MySqlParameter("@userid", userid));
                paras.Add(new MySqlParameter("@type", type));
                paras.Add(new MySqlParameter("@content", content));
                paras.Add(new MySqlParameter("@fileids", fileIds));
                paras.Add(new MySqlParameter("@said", said));

                var maxindex = mainsql.SqlExecuteScalar($"select sa_add_index from {BIAOORDERSALEADD} where sa_id='{said}'").ToInt32();
                paras.Add(new MySqlParameter("@max", maxindex + 1));
                if (status == 1)
                {
                    mainsql.SqlExcuteNoReturn($"update {BIAOORDERSALE} set sa_status=1 where sa_id='{said}'");
                }
                if (mainsql.SqlExcuteNoReturn($"insert into {BIAOORDERSALEADD}(sa_id,sa_add_create_time,sa_add_create_user,sa_add_type,sa_add_content,sa_add_file_ids,sa_add_index)"
                     + "values(@said,NOW(),@userid,@type,@content,@fileids,@max)", paras.ToArray()) == -1)
                {
                    ret.Map_Args["ErrorMsg"] = "数据插入失败";
                    mainsql.closesql();
                    goto EXIT;
                }

                //如果有附件图片，转成永久
                if (!string.IsNullOrWhiteSpace(fileIds))
                    ConvertTemporary(mainsql, fileIds);

                ret.Map_Args["ErrorMsg"] = "成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 申请客服处理
        [WebMethod(Description = "申请客服处理")]
        public string Shop_OrderSaleSystem(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_OrderSaleSystem) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                var said = comrcv.Map_Args["sa_id"]; //售后id
                var userid = comrcv.Map_Args["userid"]; //当前用户ID
                var shopid = comrcv.Map_Args.ContainsKey("ShopId") ? comrcv.Map_Args["ShopId"] : string.Empty; //店铺ID,可空。空表示买家。

                var paras = new List<MySqlParameter>();
                paras.Add(new MySqlParameter("@userid", userid));
                paras.Add(new MySqlParameter("@type", string.IsNullOrWhiteSpace(shopid) ? "0" : "1"));
                paras.Add(new MySqlParameter("@content", "申请客服处理"));
                paras.Add(new MySqlParameter("@said", said));

                mainsql.SqlExcuteNoReturn($"update {BIAOORDERSALE} set sa_status=2 where sa_id='{said}'");

                var maxindex = mainsql.SqlExecuteScalar($"select sa_add_index from {BIAOORDERSALEADD} where sa_id='{said}'").ToInt32();
                paras.Add(new MySqlParameter("@max", maxindex + 1));

                if (mainsql.SqlExcuteNoReturn($"insert into {BIAOORDERSALEADD}(sa_id,sa_add_create_time,sa_add_create_user,sa_add_type,sa_add_content,sa_add_file_ids,sa_add_index)"
                     + "values(@said,NOW(),@userid,@type,@content,'',@max)", paras.ToArray()) == -1)
                {
                    ret.Map_Args["ErrorMsg"] = "数据插入失败";
                    mainsql.closesql();
                    goto EXIT;
                }


                ret.Map_Args["ErrorMsg"] = "成功";
                mainsql.closesql();
                ret.Byte_Flag = (sbyte)1;
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 分页查询分成订单（列表管理）
        [WebMethod(Description = "分页查询分成订单（列表管理）")]
        public string Shop_GetFenChengOrderPage(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_GetFenChengOrderPage) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var shopId = comrcv.Map_Args["ShopId"];
                    var pageIndex = comrcv.Map_Args["pageIndex"].ToInt32();
                    pageIndex = pageIndex == 0 ? 1 : pageIndex;
                    var pageSize = comrcv.Map_Args["pageSize"].ToInt32();
                    pageSize = pageSize == 0 ? 10 : pageSize;

                    var shop = mainsql.SqlExecuteScalar(string.Format("select shop_id from {0} where shop_id='{1}' and shop_deleteflag=0", BIAOSHOP, shopId))?.ToString();
                    if (string.IsNullOrWhiteSpace(shopId))
                    {
                        ret.Map_Args["ErrorMsg"] = "不存在的店铺";
                        mainsql.closesql();
                        goto EXIT;
                    }

                    StringBuilder sql = new StringBuilder();
                    sql.AppendFormat("select t1.*,t2.user_name,t3.user_companyname from {0} t1 left join {1} t2 on t1.user_id=t2.user_onlyid left join {2} t3 on t1.companyid=t3.user_id where shop_id='{3}'", BIAOORDERFENCHENG, BIAOUSER, BIAOUSERCOMPANY, shopId);
                    var paras = new List<MySqlParameter>();

                    sql.AppendFormat(" order by order_createtime desc limit {0},{1}", pageIndex * pageSize - pageSize, pageSize);

                    var lis = mainsql.SqlExcuteWithReturn(sql.ToString(), paras.ToArray()).ToModels();
                    foreach (var item in lis)
                    {
                        item.Remove("prd_deleteflag");
                    }
                    ret.Maplist_MapArgs.Add("Datas", lis);

                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #endregion

        #region 询价

        private const string BIAOXUNJIA = "s_xunjia";
        private const string BIAOBAOJIA = "s_baojia";

        #region 卖家查看询价列表
        [WebMethod(Description = "卖家查看询价列表")]
        public string Shop_ShopXunJiaList(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_ShopXunJiaList) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var shopId = comrcv.Map_Args["ShopId"];
                    var starttime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                    var endtime = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
                    if (mainsql.SqlExecuteScalar($"select allxunjia from s_allshop where shop_id='{shopId}'").ToInt32() == 1)
                    {
                        var list = mainsql.SqlExcuteWithReturn($"select t1.*,t2.user_name,t2.user_phone from {BIAOXUNJIA + DateTime.Now.ToString("yyyyMM")} t1 left join {BIAOUSER} t2 on t1.user_id=t2.user_onlyid where x_deleteflag=0 and x_send_time >='{starttime}' and x_send_time<'{endtime}' order by x_send_time desc").ToModels();

                        ret.Maplist_MapArgs.Add("Model", list);
                        if (list.Count > 0)
                        {
                            var ids = string.Join(",", list.Where(x => !string.IsNullOrWhiteSpace(x["x_img_ids"])).Select(x => x["x_img_ids"])).Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                            if (ids.Length > 0)
                            {
                                var files = mainsql.SqlExcuteWithReturn($"select file_id,file_path from {BIAOSHOPFILE} where file_id in('{string.Join("','", ids)}')").ToModels();
                                ret.Maplist_MapArgs.Add("Files", files);
                            }
                            var ss = string.Join(",", list.Where(x => x["x_number"].ToInt32() > 0).Select(x => x["x_id"]).ToArray());
                            if (ss.Length > 0)
                            {
                                var sss = mainsql.SqlExcuteWithReturn($"select * from {BIAOBAOJIA + DateTime.Now.ToString("yyyyMM")} where x_id in ({ss}) and shop_id='{shopId}'").ToModels();
                                ret.Maplist_MapArgs.Add("BaoJia", sss);
                            }
                        }
                    }
                    else
                    {
                        var shopTags = mainsql.SqlExecuteScalar($"select shop_ation from {BIAOSHOP} where shop_id='{shopId}'")?.ToString()?.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                        var carids = mainsql.SqlExcuteWithReturn($"select car_type_id from {BIAOSHOPCAR} where shop_id='{shopId}'").ToModels().Select(x => x["car_type_id"]).ToList();
                        if (carids.Count > 0)
                        {
                            var datas = mainsql.SqlExcuteWithReturn($"select t1.*,t2.user_name,t2.user_phone,t5.tg_tag from {BIAOXUNJIA + DateTime.Now.ToString("yyyyMM")} t1 left join {BIAOUSER} t2 on t1.user_id=t2.user_onlyid left join {BIAOUSERCOMPANY} t3 on t2.companyid=t3.user_id left join {BIAOSHOP} t4 on t3.user_tuiguangma=t4.shop_tuiguangma left join s_allshop t5 on t4.shop_id=t5.shop_id where x_deleteflag=0 and x_send_time >='{starttime}' and x_send_time<'{endtime}' order by x_send_time desc").ToModels();


                            var list = new List<Dictionary<string, string>>();
                            foreach (var item in datas)
                            {
                                var istrue = true;
                                //if (!string.IsNullOrWhiteSpace(item["tg_tag"]))
                                //{
                                //    if (shopTags != null && shopTags.Length > 0)
                                //        istrue = shopTags.Contains(item["tg_tag"]);
                                //    else istrue = false;
                                //}
                                if (istrue)
                                {
                                    istrue = false;
                                    carids.ForEach(x => { if (!istrue) istrue = item["x_car_id"].IndexOf(x) != -1; });
                                }
                                if (istrue)
                                {
                                    list.Add(item);
                                }
                            }



                            ret.Maplist_MapArgs.Add("Model", list);
                            if (list.Count > 0)
                            {
                                var ids = string.Join(",", list.Where(x => !string.IsNullOrWhiteSpace(x["x_img_ids"])).Select(x => x["x_img_ids"])).Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                                if (ids.Length > 0)
                                {
                                    var files = mainsql.SqlExcuteWithReturn($"select file_id,file_path from {BIAOSHOPFILE} where file_id in('{string.Join("','", ids)}')").ToModels();
                                    ret.Maplist_MapArgs.Add("Files", files);
                                }
                                var ss = string.Join(",", list.Where(x => x["x_number"].ToInt32() > 0).Select(x => x["x_id"]).ToArray());
                                if (ss.Length > 0)
                                {
                                    var sss = mainsql.SqlExcuteWithReturn($"select * from {BIAOBAOJIA + DateTime.Now.ToString("yyyyMM")} where x_id in ({ss}) and shop_id='{shopId}'").ToModels();
                                    ret.Maplist_MapArgs.Add("BaoJia", sss);
                                }
                            }
                        }
                    }
                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 买家查看自己的询价列表

        [WebMethod(Description = "买家查看自己的询价列表")]
        public string Shop_XunJiaList(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_XunJiaList) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var userid = comrcv.Map_Args["userid"];
                    var time = comrcv.Map_Args["Time"];//yyyy-MM 或者当前时间
                    time = time.ToDateTime().Value.ToString("yyyy-MM").Substring(0, 7) + "-01";
                    var starttime = time;
                    var endtime = time.ToDateTime().Value.AddMonths(1).ToString("yyyy-MM-dd");
                    var list = mainsql.SqlExcuteWithReturn($"select t1.*,t2.user_name,t2.user_phone from {BIAOXUNJIA + time.ToDateTime().Value.ToString("yyyyMM")} t1 left join {BIAOUSER} t2 on t1.user_id=t2.user_onlyid where x_deleteflag=0 and x_send_time >='{starttime}' and x_send_time<'{endtime}' and user_id='{userid}' order by x_send_time desc").ToModels();
                    ret.Maplist_MapArgs.Add("Model", list);
                    if (list.Count > 0)
                    {
                        var ids = string.Join(",", list.Where(x => !string.IsNullOrWhiteSpace(x["x_img_ids"])).Select(x => x["x_img_ids"])).Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                        if (ids.Length > 0)
                        {
                            var files = mainsql.SqlExcuteWithReturn($"select file_id,file_path from {BIAOSHOPFILE} where file_id in('{string.Join("','", ids)}')").ToModels();
                            ret.Maplist_MapArgs.Add("Files", files);
                        }
                    }


                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 买家发布询价信息
        [WebMethod(Description = "买家发布询价信息")]
        public string Shop_XunJiaAdd(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info($"Shop_XunJiaAdd:{msg}");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {

                    var userid = comrcv.Map_Args["userid"];
                    loginfo.Info("买家发布询价信息:" + userid);
                    var content = comrcv.Map_Args["Content"];
                    var fileIds = comrcv.Map_Args["files"];
                    var ids = comrcv.Map_Args["carid"].Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries).ToArray();
                    var carid = string.Join(",", ids);
                    var products = comrcv.Map_Args["products"];

                    JArray productsJson = JsonConvert.DeserializeObject<JArray>(products);
                    string productscount = productsJson.Count.ToString();
                    string productsnames = "";
                    if (productsJson != null && productsJson.Count > 0)
                    {
                        foreach (var item in productsJson)
                        {
                            productsnames += "【" + item.Value<string>("name") + "】";

                        }
                    }

                    #region 获取车辆价格信息

                    var proInfo = Helper.GetShichedao(content, productsJson, loginfo);
                    products = string.IsNullOrWhiteSpace(proInfo) ? products : proInfo;

                    #endregion


                    if (mainsql.SqlExecuteScalar($"select count(*) from information_schema.TABLES t where t.TABLE_SCHEMA ='yonghusystem' and t.TABLE_NAME ='{BIAOXUNJIA + DateTime.Now.ToString("yyyyMM")}'").ToInt32() == 0)
                    {
                        mainsql.SqlExcuteNoReturn($"CREATE TABLE `{BIAOXUNJIA + DateTime.Now.AddMonths(3).ToString("yyyyMM")}` (" +
                              "`x_id` bigint(20) NOT NULL AUTO_INCREMENT," +
                              "`user_id` varchar(36) NOT NULL," +
                              "`x_content` varchar(500) DEFAULT NULL COMMENT '聊天的文本内容'," +
                              "`x_img_ids` varchar(500) DEFAULT NULL COMMENT '聊天的图片文件地址'," +
                              "`x_send_time` datetime NOT NULL," +
                              "`x_deleteflag` tinyint(4) DEFAULT '0'," +
                              "`x_car_id` varchar(500) DEFAULT NULL," +
                              "`x_number` int DEFAULT '0'," +
                              "`x_products` text," +
                              "`order_id` bigint(20) DEFAULT NULL," +
                              "PRIMARY KEY(`x_id`)," +
                              "KEY `Index_2` (`x_send_time`)" +
                              ") ENGINE = InnoDB DEFAULT CHARSET = utf8");
                    }

                    string newxunjiaid = getxunjiaid(mainsql);

                    if (mainsql.SqlExcuteNoReturn($"insert into {BIAOXUNJIA + DateTime.Now.ToString("yyyyMM")}(xj_id,user_id,x_content,x_img_ids,x_send_time,x_deleteflag,x_car_id,x_products,x_number) "
                         + $"values('{newxunjiaid}','{userid}','{content}','{fileIds}',NOW(),0,'{carid}',@product,0)", new MySqlParameter("@product", products)) != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "服务器异常";
                        goto EXIT;
                    }
                    //如果有附件图片，转成永久
                    if (!string.IsNullOrWhiteSpace(fileIds))
                        ConvertTemporary(mainsql, fileIds);


                    //添加留言记录
                    //获取询价车架号
                    string msgPr = "我已发布询价";
                    if (!string.IsNullOrWhiteSpace(content))
                    {
                        try
                        {
                            JArray jar = JArray.Parse(content);

                            if (jar != null && jar[2] != null)
                            {
                                msgPr = $"{msgPr}，车架号：{jar[2]}";
                            }

                            if (mainsql.SqlExecuteScalar($"select count(*) from yonghuallusercar where car_carvin ='{jar[2]}' and car_userid='{userid}'").ToInt32() == 0)
                            {
                                string carInfo = "{\"brand\":\"" + jar[1][0].ToString().Split(':')[1] + "\",\"yeartype\":\"" + jar[1][1].ToString().Split(':')[1] + "\",\"name\":\"" + jar[1][2].ToString().Split(':')[1] + "\",\"typename\":\"" + jar[1][3].ToString().Split(':')[1] + "\",\"vin\":\"" + jar[2] + "\"}";

                                loginfo.Info($"select * from {BIAOUSER} where  user_onlyid='{userid}'");
                                var carUser = mainsql.SqlExcuteWithReturn($"select * from {BIAOUSER} where  user_onlyid='{userid}'").ToModels().FirstOrDefault();
                                if (carUser != null)
                                {
                                    string intsertkeystr = SQLUSERCAR;
                                    string intsertvaluestr = SQLUSERCAR;
                                    intsertvaluestr = intsertvaluestr.Replace("car_userid", "'" + userid + "'");
                                    intsertvaluestr = intsertvaluestr.Replace("car_userphone", "'" + carUser["user_phone"] + "'");
                                    intsertvaluestr = intsertvaluestr.Replace("car_username", "'" + carUser["user_name"] + "'");
                                    intsertvaluestr = intsertvaluestr.Replace("car_carplate", "''");
                                    intsertvaluestr = intsertvaluestr.Replace("car_carvin", "'" + jar[2] + "'");
                                    intsertvaluestr = intsertvaluestr.Replace("car_carinfo", "'" + carInfo + "'");
                                    intsertvaluestr = intsertvaluestr.Replace("car_default", "''");

                                    string cmd = string.Format("insert into {0} ({1}) values ({2}) ", USERCAR, intsertkeystr, intsertvaluestr);
                                    loginfo.Info(cmd);
                                    int sqlret = mainsql.SqlExcuteNoReturn(cmd);
                                    if (sqlret != 1)
                                    {
                                        loginfo.Info("加入爱车失败");
                                    }
                                }

                            }
                        }
                        catch
                        {

                        }

                    }
                    //获取询价商品
                    if (!string.IsNullOrWhiteSpace(products))
                    {
                        try
                        {
                            JArray jar = JArray.Parse(products);

                            if (jar != null && jar[0] != null)
                            {
                                msgPr = $"{msgPr}，产品名称：{jar[0]["name"]}。";
                            }
                        }
                        catch
                        {

                        }
                    }
                    var shopSysId = ConfigurationManager.AppSettings["SystemMsg"].ToString();//接收者
                    var paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@ShopId", shopSysId));
                    paras.Add(new MySqlParameter("@FromUserId", userid));
                    paras.Add(new MySqlParameter("@Content", msgPr));
                    paras.Add(new MySqlParameter("@imgFileId", ""));
                    paras.Add(new MySqlParameter("@JsonString", ""));

                    var id = mainsql.SqlExecuteScalar($"insert into {BIAOMSG}(shop_id,chart_isbuyer,user_id,chart_from_user_id,chart_content,chart_img_id,chart_json,chart_send_time,chart_isread)values"
                        + "(@ShopId,0,@FromUserId,@FromUserId,@Content,@imgFileId,@JsonString,NOW(),0);SELECT @@IDENTITY", paras.ToArray()).ToString();
                    ret.Map_Args.Add("MsgId", id);

                    mainsql.SqlExcuteNoReturn($"update {BIAOMSG} set chart_isread=1,chart_read_user_id='{userid}' where shop_id='{shopSysId}' and chart_isread=0 and chart_isbuyer=1 and user_id='{userid}'");

                    #region 发微信消息
                    var usersWacht = mainsql.SqlExcuteWithReturn($"select * from {BIAOUSER} where user_customer_type=1").ToModels();//取出平台客服
                    var userWacht = mainsql.SqlExcuteWithReturn($"select * from {BIAOUSER} where user_onlyid='{userid}'").ToModels();//发送人

                    foreach (var item in usersWacht)
                    {
                        var openid = item["user_openid_juhesheng"];
                        if (!string.IsNullOrWhiteSpace(openid))
                        {
                            //发送消息
                            WebServiceShopping.wechartTools.SendMsg(new WebServiceShopping.wechartTools.ConsultantMsg()
                            {
                                miniprogram = new WebServiceShopping.wechartTools.XCXPath()
                                {
                                    pagepath = "pages/my/msg1/msg"
                                },
                                touser = openid,
                                data = new WebServiceShopping.wechartTools.ConsultantMsg.DataModel()
                                {
                                    keyword1 = new WebServiceShopping.wechartTools.DataItem()
                                    {
                                        value = userWacht[0]["user_name"]
                                    },
                                    keyword2 = new WebServiceShopping.wechartTools.DataItem()
                                    {
                                        value = userWacht[0]["user_phone"]
                                    },
                                    keyword3 = new WebServiceShopping.wechartTools.DataItem()
                                    {
                                        value = DateTime.Now.ToString("yyyy年MM月dd HH:mm:ss")
                                    }
                                }
                            });
                        }
                    }
                    #endregion



                    //查询有没有特殊推广分成
                    //var tgtag = mainsql.SqlExecuteScalar($"select tg_tag from {BIAOUSER} t2 left join {BIAOUSERCOMPANY} t3 on t2.companyid=t3.user_id left join {BIAOSHOP} t4 on t3.user_tuiguangma=t4.shop_tuiguangma left join s_allshop t5 on t4.shop_id=t5.shop_id"
                    //    + " where t2.user_onlyid='" + userid + "'")?.ToString();
                    //{(string.IsNullOrWhiteSpace(tgtag) ? "" : " and shop_ation like '%" + tgtag + "%'")}
                    var shopids = mainsql.SqlExcuteWithReturn($"select shop_id from {BIAOSHOPCAR} t1 where t1.car_type_id in ('{string.Join("','", ids)}') and t1.shop_car_deleteflag=0  group by shop_id").ToModels();

                    #region 发微信消息
                    var userIds = new List<string>();
                    foreach (var item in shopids)
                    {
                        var shopId = item["shop_id"];
                        var users = mainsql.SqlExcuteWithReturn($"select t2.user_openid_juhesheng,t2.user_phone,t2.user_name,t2.user_onlyid from {BIAOSHOPUSER} t1 left join {BIAOUSER} t2 on t1.user_id=t2.user_onlyid where shop_id='{shopId}' and shop_user_ismsg=1 and shop_user_deleteflag<>1").ToModels();
                        foreach (var uitem in users)
                        {
                            var openid = uitem["user_openid_juhesheng"];
                            if (!string.IsNullOrWhiteSpace(openid))
                            {
                                userIds.Add(uitem["user_onlyid"]);
                                //发送消息
                                WebServiceShopping.wechartTools.SendMsgGZH(new WebServiceShopping.wechartTools.XunJiaMsg()
                                {
                                    miniprogram = new WebServiceShopping.wechartTools.XCXPath()
                                    {
                                        pagepath = "/pages/my/store/store?ShopId=" + shopId
                                    },
                                    touser = openid,
                                    data = new WebServiceShopping.wechartTools.XunJiaMsg.DataModel()
                                    {
                                        first = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = "您有新的询价单"
                                        },
                                        keyword2 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = DateTime.Now.ToString("yyyy年MM月dd HH:mm")
                                        },
                                        keyword3 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = productsnames
                                        },
                                        keyword1 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = "实际询价人"
                                        },
                                        keyword4 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = productscount
                                        }
                                    }
                                });
                            }
                        }
                    }

                    shopids = mainsql.SqlExcuteWithReturn($"select shop_id from s_allshop where allxunjia='1'").ToModels();
                    foreach (var item in shopids)
                    {
                        var shopId = item["shop_id"];
                        var users = mainsql.SqlExcuteWithReturn($"select t2.user_openid_juhesheng,t2.user_phone,t2.user_name,t2.user_onlyid from {BIAOSHOPUSER} t1 left join {BIAOUSER} t2 on t1.user_id=t2.user_onlyid where shop_id='{shopId}' and shop_user_ismsg=1 and shop_user_deleteflag<>1").ToModels();
                        foreach (var uitem in users)
                        {
                            var openid = uitem["user_openid_juhesheng"];
                            if (!string.IsNullOrWhiteSpace(openid))
                            {
                                userIds.Add(uitem["user_onlyid"]);
                                //发送消息
                                WebServiceShopping.wechartTools.SendMsgGZH(new WebServiceShopping.wechartTools.XunJiaMsg()
                                {
                                    miniprogram = new WebServiceShopping.wechartTools.XCXPath()
                                    {
                                        pagepath = "/pages/my/store/store?ShopId=" + shopId
                                    },
                                    touser = openid,
                                    data = new WebServiceShopping.wechartTools.XunJiaMsg.DataModel()
                                    {
                                        first = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = "您有新的询价单"
                                        },
                                        keyword2 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = DateTime.Now.ToString("yyyy年MM月dd HH:mm")
                                        },
                                        keyword3 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = productsnames
                                        },
                                        keyword1 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = "合作修理厂"
                                        },
                                        keyword4 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = productscount
                                        }
                                    }
                                });
                            }
                        }
                    }


                    var ps = mainsql.SqlExecuteScalar($"select c_name from {BIAOSHOPCONFIG} where c_type='xunjiamsg'")?.ToString();
                    if (!string.IsNullOrWhiteSpace(ps))
                    {
                        loginfo.Error(ps);
                        var ss = ps.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                        if (ss.Length > 0)
                        {
                            var users = mainsql.SqlExcuteWithReturn($"select user_openid_juhesheng,user_phone,user_name,user_onlyid from {BIAOUSER} where user_phone in ('{string.Join("','", ss)}')").ToModels();
                            foreach (var item in users)
                            {
                                if (!userIds.Contains(item["user_onlyid"]))
                                {
                                    var openid = item["user_openid_juhesheng"];
                                    loginfo.Error(openid);
                                    if (!string.IsNullOrWhiteSpace(openid))
                                    {
                                        WebServiceShopping.wechartTools.SendMsg(new WebServiceShopping.wechartTools.OrderMsg()
                                        {
                                            miniprogram = null,
                                            touser = openid,
                                            data = new WebServiceShopping.wechartTools.OrderMsg.DataModel()
                                            {
                                                first = new WebServiceShopping.wechartTools.DataItem()
                                                {
                                                    value = "有新的询价需求单"
                                                },
                                                keyword2 = new WebServiceShopping.wechartTools.DataItem()
                                                {
                                                    value = ""
                                                },
                                                keyword3 = new WebServiceShopping.wechartTools.DataItem()
                                                {
                                                    value = DateTime.Now.ToString("yyyy年MM月dd HH:mm")
                                                },
                                                keyword1 = new WebServiceShopping.wechartTools.DataItem()
                                                {
                                                    value = "询价需求单"
                                                },
                                                remark = new WebServiceShopping.wechartTools.DataItem()
                                                {
                                                    value = "此通知消息为默认通知，无法直接查看详情。"
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                        }
                    }



                    #endregion

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 买家删除询价信息

        [WebMethod(Description = "买家删除询价信息")]
        public string Shop_XunJiaDel(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_XunJiaDel) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var id = comrcv.Map_Args["x_id"];

                    var time = comrcv.Map_Args["Time"];//yyyy-MM 或者当前时间
                    time = time.ToDateTime().Value.ToString("yyyy-MM").Substring(0, 7) + "-01";

                    mainsql.SqlExcuteNoReturn($"update {BIAOXUNJIA + time.ToDateTime().Value.ToString("yyyyMM")} set x_deleteflag=1 where x_id='{id}'");

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 卖家报价

        [WebMethod(Description = "卖家报价")]
        public string Shop_XunJiaShop(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");

            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
            mysqlcli mainsql = new mysqlcli();
#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var id = comrcv.Map_Args["x_id"];
                    var bid = comrcv.Map_Args.ContainsKey("b_id") ? comrcv.Map_Args["b_id"] : string.Empty;
                    var userid = comrcv.Map_Args["userid"];
                    var shopId = comrcv.Map_Args["ShopId"];
                    var price = comrcv.Map_Args["Price"];
                    var products = comrcv.Map_Args["products"];
                    var descript = comrcv.Map_Args["Descript"];
                    var time = comrcv.Map_Args["Time"];//yyyy-MM 或者当前时间
                    time = time.ToDateTime().Value.ToString("yyyy-MM").Substring(0, 7) + "-01";
                    var fileIds = comrcv.Map_Args.ContainsKey("files") ? comrcv.Map_Args["files"] : string.Empty;


                    if (string.IsNullOrWhiteSpace(bid))
                    {
                        if (mainsql.SqlExcuteNoReturn($"insert into {BIAOBAOJIA + time.ToDateTime().Value.ToString("yyyyMM")}(x_id,shop_id,user_id,b_price,b_descript,b_products,b_img_ids,b_createtime) values(@id,@shopid,@userid,@price,@descript,@product,@files,NOW())"
                            , new MySqlParameter("@id", id), new MySqlParameter("@shopid", shopId), new MySqlParameter("@userid", userid), new MySqlParameter("@price", price), new MySqlParameter("@descript", descript), new MySqlParameter("@product", products), new MySqlParameter("@files", fileIds)) != 1)
                        {
                            ret.Map_Args["ErrorMsg"] = "操作失败";
                            mainsql.closesql();
                            goto EXIT;
                        }
                        mainsql.SqlExcuteNoReturn($"update {BIAOXUNJIA + time.ToDateTime().Value.ToString("yyyyMM")} set x_number=x_number+1 where x_id='{id}'");
                    }
                    else
                    {
                        if (mainsql.SqlExcuteNoReturn($"update {BIAOBAOJIA + time.ToDateTime().Value.ToString("yyyyMM")} set x_id=@id,shop_id=@shopid,user_id=@userid,b_price=@price,b_descript=@descript,b_products=@product,b_img_ids=@files,b_createtime=NOW() where b_id=@bid"
                            , new MySqlParameter("@id", id), new MySqlParameter("@bid", bid), new MySqlParameter("@shopid", shopId), new MySqlParameter("@userid", userid), new MySqlParameter("@price", price), new MySqlParameter("@descript", descript), new MySqlParameter("@product", products), new MySqlParameter("@files", fileIds)) != 1)
                        {
                            ret.Map_Args["ErrorMsg"] = "操作失败";
                            mainsql.closesql();
                            goto EXIT;
                        }
                    }

                    //如果有附件图片，转成永久
                    if (!string.IsNullOrWhiteSpace(fileIds))
                        ConvertTemporary(mainsql, fileIds);

                    #region 发微信消息
                    string openid = "";
                    #region 给修理厂发微信消息
                    string cmd = string.Format($"select repair_id from {BIAOXUNJIA + time.ToDateTime().Value.ToString("yyyyMM")}  where x_id='{id}'");
                    var repair_id = mainsql.SqlExecuteScalar(cmd).ToString();
                    if (!string.IsNullOrWhiteSpace(repair_id))
                    {
                        cmd = string.Format($"select * from {BIAOUSERREPAIR}  where repair_id='{repair_id}'");
                        DataTable ds = mainsql.SqlExcuteWithReturn(cmd);
                        if (ds.Rows.Count == 0)
                        {

                            mainsql.closesql();
                            goto EXIT;
                        }
                        string repair_companyid = ds.Rows[0]["repair_companyid"].ToString();
                        string repair_carplate = ds.Rows[0]["repair_carplate"].ToString();

                        string repair_yonghuname = ds.Rows[0]["repair_yonghuname"].ToString();

                        var user_binduserid = mainsql.SqlExecuteScalar($"select user_binduserid from {BIAOUSERCOMPANY} where user_id='{repair_companyid}'").ToString();
                        var ids = user_binduserid.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                        var user_onlyids = string.Join("','", ids);
                        var userModel = mainsql.SqlExcuteWithReturn($"select user_openid_juhesheng from {BIAOUSER} where user_phone IN ('{user_onlyids}')  ").ToModels();

                        foreach (var uitem in userModel)
                        {
                            openid = uitem["user_openid_juhesheng"];

                            if (!string.IsNullOrWhiteSpace(openid))
                            {
                                WebServiceShopping.wechartTools.SendMsgGZH(new WebServiceShopping.wechartTools.BaoJiaMsg()
                                {
                                    miniprogram = new WebServiceShopping.wechartTools.XCXPath()
                                    {
                                        pagepath = $"/pages/my/repairfactory/index/index?companyid={repair_companyid}"
                                    },
                                    touser = openid,
                                    data = new WebServiceShopping.wechartTools.BaoJiaMsg.DataModel()
                                    {
                                        first = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = "您的询价单有商家进行报价！"
                                        },
                                        keyword1 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = $"【{repair_yonghuname}】-({repair_carplate})"
                                        },
                                        keyword2 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = "正常报价"
                                        },
                                        keyword3 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = price
                                        },
                                        keyword4 = new WebServiceShopping.wechartTools.DataItem()
                                        {
                                            value = DateTime.Now.ToString("yyyy年MM月dd HH:mm")
                                        }
                                    }
                                });
                            }
                        }
                    }

                    #endregion

                    #region 给用户发微信消息
                    openid = mainsql.SqlExecuteScalar($"select user_openid_juhesheng from {BIAOXUNJIA + time.ToDateTime().Value.ToString("yyyyMM")} left join {BIAOUSER} on user_id=user_onlyid where x_id='{id}' and user_ismsg='1'")?.ToString();
                    var shopName = mainsql.SqlExecuteScalar($"select shop_name from {BIAOSHOP} where shop_id='{shopId}'").ToString();

                    if (!string.IsNullOrWhiteSpace(openid))
                    {
                        //发送消息
                        WebServiceShopping.wechartTools.SendMsg(new WebServiceShopping.wechartTools.OrderMsg()
                        {
                            miniprogram = new WebServiceShopping.wechartTools.XCXPath()
                            {
                                pagepath = "/pages/xunjia/xunjia"
                            },
                            touser = openid,
                            data = new WebServiceShopping.wechartTools.OrderMsg.DataModel()
                            {
                                first = new WebServiceShopping.wechartTools.DataItem()
                                {
                                    value = "您的询价需求单有新的报价信息"
                                },
                                keyword2 = new WebServiceShopping.wechartTools.DataItem()
                                {
                                    value = ""
                                },
                                keyword3 = new WebServiceShopping.wechartTools.DataItem()
                                {
                                    value = DateTime.Now.ToString("yyyy年MM月dd HH:mm")
                                },
                                keyword1 = new WebServiceShopping.wechartTools.DataItem()
                                {
                                    value = "询价需求单"
                                }
                            }
                        });
                    }

                    #endregion
                    #endregion
                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 查看报价信息

        [WebMethod(Description = "查看报价信息")]
        public string Shop_BaoJiaList(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info("查看报价信息:");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var id = comrcv.Map_Args["x_id"];
                    var time = comrcv.Map_Args["Time"];//yyyy-MM 或者当前时间
                    time = time.ToDateTime().Value.ToString("yyyy-MM").Substring(0, 7) + "-01";

                    var list = mainsql.SqlExcuteWithReturn($"select t1.*,t2.shop_name,shop_ation,shop_tel_number from {BIAOBAOJIA + time.ToDateTime().Value.ToString("yyyyMM")} t1 left join {BIAOSHOP} t2 on t1.shop_id=t2.shop_id where t1.x_id='{id}'").ToModels();

                    if (list.Count > 0)
                    {
                        var ids = string.Join(",", list.Where(x => !string.IsNullOrWhiteSpace(x["b_img_ids"])).Select(x => x["b_img_ids"])).Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries);
                        if (ids.Length > 0)
                        {
                            var files = mainsql.SqlExcuteWithReturn($"select file_id,file_path from {BIAOSHOPFILE} where file_id in('{string.Join("','", ids)}')").ToModels();
                            ret.Maplist_MapArgs.Add("Files", files);
                        }
                    }

                    var xj_id = mainsql.SqlExecuteScalar($"select xj_id from {BIAOXUNJIA + time.ToDateTime().Value.ToString("yyyyMM")}  where x_id='{id}'").ToString();

                    var dt = mainsql.SqlExcuteWithReturn($"select t1.*,t2.user_companyname as shop_name,user_flag as shop_ation ,user_companytel as shop_tel_number  from {BIAOBAOJIA + time.ToDateTime().Value.ToString("yyyyMM")} t1 left join {BIAOUSERCOMPANY} t2 on t1.shop_id=t2.user_id where t1.x_id='{xj_id}'");

                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow item in dt.Rows)
                        {
                            var model = new Dictionary<string, string>();
                            foreach (DataColumn cItem in dt.Columns)
                            {
                                if (!model.ContainsKey(cItem.ColumnName))
                                {
                                    model.Add(cItem.ColumnName, item[cItem.ColumnName]?.ToString() ?? string.Empty);
                                }
                            }
                            list.Add(model);
                        }
                    }


                    ret.Maplist_MapArgs.Add("Datas", list);



                    dt = mainsql.SqlExcuteWithReturn($"select t1.x_id,t2.user_companyname ,t2.user_companytel ,t2.user_companypath from {BIAOXUNJIA + time.ToDateTime().Value.ToString("yyyyMM")} t1 left join {BIAOUSERCOMPANY} t2 on t1.user_id=t2.user_id where t1.x_id='{id}'  ");

                    ret.Maplist_MapArgs.Add("XLCDatas", dt.ToModels());


                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #endregion

        #region 配置信息

        [WebMethod(Description = "配置信息")]
        public string Shop_ShopConfig(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_ShopConfig) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var type = comrcv.Map_Args["type"];
                    /**
                     * dingdanquxiaobuyer  订单取消原因(买家)
                     * dingdanquxiaoshop   订单取消原因(店铺)
                     * pingjiayes          满意评价
                     * pingjiano           不满意评价
                     * banner              首页图片
                     * */
                    ret.Maplist_MapArgs.Add("Datas", mainsql.SqlExcuteWithReturn($"select * from {BIAOSHOPCONFIG} where c_type='{type}' {(type == "banner" ? "" : "and c_parent_id is not null")} order by c_index").ToModels());


                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 店铺银行卡管理
        private const string BIAOBANKCARD = "s_bankcard";

        #region 列表查询

        [WebMethod(Description = "列表查询")]
        public string Shop_CardList(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerBankCard");
            loginfo.Info(nameof(Shop_CardList) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var shopid = comrcv.Map_Args["ShopId"];
                    ret.Maplist_MapArgs.Add("Datas", mainsql.SqlExcuteWithReturn($"select * from {BIAOBANKCARD} where shop_id='{shopid}' and bank_deleteflag=0").ToModels());

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 添加/编辑

        [WebMethod(Description = "添加/编辑")]
        public string Shop_ModifyCard(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerBankCard");
            loginfo.Info(nameof(Shop_ModifyCard) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var shopid = comrcv.Map_Args["ShopId"]; //店铺ID
                    var id = comrcv.Map_Args["bank_id"].ToInt32(); //原ID，如果有就是编辑
                    var name = comrcv.Map_Args["bank_name"];  //银行名
                    var number = comrcv.Map_Args["bank_cardnumber"]; //卡号
                    var username = comrcv.Map_Args["bank_username"]; //开户名
                    var isdefault = comrcv.Map_Args["bank_isdefault"].ToInt32(); //0不默认，1默认

                    var paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@shopid", shopid));
                    paras.Add(new MySqlParameter("@bank_name", name));
                    paras.Add(new MySqlParameter("@bank_cardnumber", number));
                    paras.Add(new MySqlParameter("@bank_username", username));
                    paras.Add(new MySqlParameter("@bank_isdefault", isdefault));
                    paras.Add(new MySqlParameter("@id", id));
                    if (isdefault == 1)
                    {
                        mainsql.SqlExcuteNoReturn($"update {BIAOBANKCARD} set bank_isdefault=0 where shop_id=@shopid", paras.ToArray());
                    }
                    if (id > 0)
                    {
                        mainsql.SqlExcuteNoReturn($"update {BIAOBANKCARD} set bank_name=@bank_name,bank_cardnumber=@bank_cardnumber,bank_username=@bank_username,bank_isdefault=@bank_isdefault where bank_id=@id and shop_id=@shopid"
                            , paras.ToArray());
                    }
                    else
                    {
                        mainsql.SqlExcuteNoReturn($"insert into {BIAOBANKCARD} (shop_id,bank_name,bank_cardnumber,bank_username,bank_isdefault,bank_deleteflag,bank_createtime)"
                            + "values(@shopid,@bank_name,@bank_cardnumber,@bank_username,@bank_isdefault,0,NOW())"
                            , paras.ToArray());
                    }
                    ret.Maplist_MapArgs.Add("Datas", mainsql.SqlExcuteWithReturn($"select * from {BIAOBANKCARD} where shop_id='{shopid}' and bank_deleteflag=0").ToModels());

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 删除

        [WebMethod(Description = "删除")]
        public string Shop_DelCard(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerBankCard");
            loginfo.Info(nameof(Shop_DelCard) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var shopid = comrcv.Map_Args["ShopId"]; //店铺ID
                    var id = comrcv.Map_Args["bank_id"].ToInt32(); //id

                    var paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@shopid", shopid));
                    paras.Add(new MySqlParameter("@id", id));
                    mainsql.SqlExcuteNoReturn($"update {BIAOBANKCARD} set bank_deleteflag=1 where bank_id=@id and shop_id=@shopid", paras.ToArray());

                    ret.Maplist_MapArgs.Add("Datas", mainsql.SqlExcuteWithReturn($"select * from {BIAOBANKCARD} where shop_id='{shopid}' and bank_deleteflag=0").ToModels());

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 设为默认

        [WebMethod(Description = "设为默认")]
        public string Shop_SetDefaultCard(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerBankCard");
            loginfo.Info(nameof(Shop_SetDefaultCard) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();

#if DEBUG
            mainsql.opensql(new SqlInfo()
            {
                String_sqlip = "127.0.0.1",
                String_sqlname = "shopping",
                String_sqlport = "3306",
                String_sqlpwd = "123456",
                String_sqluser = "root"
            });
#else
            mainsql.openShopServicesql();
#endif

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    var shopid = comrcv.Map_Args["ShopId"]; //店铺ID
                    var id = comrcv.Map_Args["bank_id"].ToInt32(); //id

                    var paras = new List<MySqlParameter>();
                    paras.Add(new MySqlParameter("@shopid", shopid));
                    paras.Add(new MySqlParameter("@id", id));

                    mainsql.SqlExcuteNoReturn($"update {BIAOBANKCARD} set bank_isdefault=0 where shop_id=@shopid", paras.ToArray());

                    mainsql.SqlExcuteNoReturn($"update {BIAOBANKCARD} set bank_isdefault=1 where bank_id=@id and shop_id=@shopid", paras.ToArray());

                    ret.Maplist_MapArgs.Add("Datas", mainsql.SqlExcuteWithReturn($"select * from {BIAOBANKCARD} where shop_id='{shopid}' and bank_deleteflag=0").ToModels());

                    ret.Map_Args["ErrorMsg"] = "操作成功";
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #endregion

        #region 会员卡

        [WebMethod(Description = "注册会员卡")]
        public ResultModel RegisterVip(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(RegisterVip) + ":" + msg);
            var result = new ResultModel()
            {
                IsSucces = false,
                Message = "操作失败"
            };
            //ComThriftMsg ret = new ComThriftMsg();
            //ret.Byte_Flag = (sbyte)-1;
            //ret.Map_Args = new Dictionary<string, string>();
            //ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            //ret.Map_Args.Add("ErrorMsg", "服务器异常");
            //byte[] bytrcv = Convert.FromBase64String(msg);
            //var isjson = true;
            //ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                var model = JsonConvert.DeserializeObject<VipModel>(msg);
                var vip_id = Guid.NewGuid().ToString();
                var vip_frame_no = model.FrameNo;//车架号
                var vip_license_plate_no = model.LicensePlateNo;//车牌号
                var vip_name = model.Nickname; //昵称
                var vip_phone = model.Phone; //电话

                string message = string.Empty;
                if (string.IsNullOrWhiteSpace(model.FrameNo))
                {
                    message += "车架号不能为空！";
                }
                if (string.IsNullOrWhiteSpace(model.LicensePlateNo))
                {
                    message += "车牌号不能为空！";
                }
                if (string.IsNullOrWhiteSpace(model.Nickname))
                {
                    message += "昵称不能为空！";
                }
                if (string.IsNullOrWhiteSpace(model.Phone))
                {
                    message += "电话不能为空！";
                }
                if (string.IsNullOrWhiteSpace(model.CarType))
                {
                    message += "汽车类型不能为空！";
                }
                if (!string.IsNullOrWhiteSpace(model.Id))
                {
                    vip_id = model.Id;

                    if (string.IsNullOrWhiteSpace(vip_id))
                    {
                        message += "Vip的ID不能为空";
                    }
                }

                if (!string.IsNullOrWhiteSpace(message))
                {
                    throw new Exception(message);
                }

                var sql = string.Empty;
                var paras = new List<MySqlParameter>();
                paras.Add(new MySqlParameter("@vip_id", vip_id));
                paras.Add(new MySqlParameter("@vip_frame_no", vip_frame_no));
                paras.Add(new MySqlParameter("@vip_license_plate_no", vip_license_plate_no));
                paras.Add(new MySqlParameter("@vip_name", vip_name));
                paras.Add(new MySqlParameter("@vip_phone", vip_phone));

                var tr = mainsql.Connection().BeginTransaction();

                //是否存在VIP信息
                sql = $"select * from s_vip where vip_frame_no='{vip_frame_no}' or vip_license_plate_no='{vip_license_plate_no}' or vip_phone='{vip_phone}';";
                var vipModel = mainsql.SqlExcuteWithReturn(sql).ToModels().FirstOrDefault();

                if (vipModel != null)
                {
                    throw new Exception("该车牌号或手机号或车架号已经被注册尊享会员卡了。");
                }

                //新增VIP信息
                sql = $@"insert into s_vip (
                            vip_id,
                            vip_frame_no,
                            vip_license_plate_no,
                            vip_name,
                            vip_phone,
                            vip_create_time,
                            vip_create_update_time
                            )values(
                            '{vip_id}',
                            '{vip_frame_no}',
                            '{vip_license_plate_no}',
                            '{vip_name}',
                            '{vip_phone}',
                            NOW(),
                            NOW());";

                mainsql.SqlExcuteNoReturn(sql, tr);

                //判断是小程序否注册了该用户
                sql = $"select * from yonghualluser where user_phone='{vip_phone}'";
                var user = mainsql.SqlExcuteWithReturn(sql).ToModels().FirstOrDefault();
                string userid = "";
                var vipType = model.CarType.Equals("1") ? 1 : 0;
                if (user == null)
                {
                    //  throw new Exception($"该手机号({vip_phone})没有注册为老顶坡汽摩小程序的用户，请关注老顶坡汽摩公众号重新注册！");
                    userid = Guid.NewGuid().ToString().ToLower();
                    mainsql.SqlExcuteNoReturn($"insert into {BIAOUSER}(user_onlyid,user_phone,user_name,vip_type) values('{userid}','{vip_phone}','{vip_name}','{vipType}')", tr);
                }
                else
                {
                    userid = user["user_onlyid"];
                    //修改用户为VIP

                    sql = $"update yonghualluser set vip_type={vipType} where user_phone='{vip_phone}'";
                    mainsql.SqlExcuteNoReturn(sql, tr);
                }


                //查找用户
                sql = $"select * from yonghuallusercar where car_userid='{userid}' and car_carvin='{vip_frame_no}'";
                var userCar = mainsql.SqlExcuteWithReturn(sql).ToModels().FirstOrDefault();


                if (userCar == null)
                {
                    //添加车库
                    string intsertkeystr = SQLUSERCAR;
                    string intsertvaluestr = SQLUSERCAR;
                    intsertvaluestr = intsertvaluestr.Replace("car_userid", "'" + userid + "'");
                    intsertvaluestr = intsertvaluestr.Replace("car_userphone", "'" + model.Phone + "'");
                    intsertvaluestr = intsertvaluestr.Replace("car_username", "'" + model.Nickname + "'");
                    intsertvaluestr = intsertvaluestr.Replace("car_carplate", "'" + model.LicensePlateNo + "'");
                    intsertvaluestr = intsertvaluestr.Replace("car_carvin", "'" + model.FrameNo + "'");
                    intsertvaluestr = intsertvaluestr.Replace("car_carinfo", "'" + JsonConvert.SerializeObject(model.CarDetail) + "'");
                    intsertvaluestr = intsertvaluestr.Replace("car_default", "''");

                    sql = string.Format("insert into {0} ({1}) values ({2}) ", USERCAR, intsertkeystr, intsertvaluestr);
                    mainsql.SqlExcuteNoReturn(sql, tr);
                    result.Message = "操作成功";
                }
                else
                {
                    result.Message = $"操作成功,该车已在车库，车架号：{vip_frame_no}";
                }
                if (vipType == 1)
                {
                    string s_couponsid = Guid.NewGuid().ToString().ToLower();
                    sql = $@"insert into s_coupon (Sid,
                            user_id,
                            user_phone,
                            coupon_createtime,
                            coupon_status,
                            coupon_describe,
                            coupon_endtime,
                            coupon_recharge_type,
                            coupon_type,
                            coupon_product_id,
                            coupon_employ,
                            coupon_source,
                            coupon_product_type,
                            coupon_company_type,
                            company_id
                            )values(
                            '{s_couponsid}',
                            '{userid}',
                            '{vip_phone}',
                            NOW(),
                            '0',
                            '会员洗车券',
                            '2023-03-31 23:59:59',
                              '1',
                              '2',
                              'all',
                              '1',
                              '0',
                              'd31e4668-9fb1-4feb-861d-4ec65e98f94f',
                              '3',
                              'all');";

                    mainsql.SqlExcuteNoReturn(sql, tr);
                }

                tr.Commit();
                result.IsSucces = true;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

            mainsql.closesql();
            return result;
        }

        #endregion


        #region 添加店铺收藏
        [WebMethod(Description = "添加店铺收藏")]
        public string S_CompanyCollect_A(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_UpdateCommodityStatus) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    string userId = comrcv.Map_Args["userId"];            //用户onlyId
                    string companyId = comrcv.Map_Args["companyId"]; //店铺ID
                    string collectId = Guid.NewGuid().ToString();//收藏ID
                    //用户是否存在
                    var sqlc = $"select * from yonghualluser where user_onlyid='{userId}'";
                    var ds = mainsql.SqlExcuteWithReturn(sqlc);
                    if (ds.Rows.Count == 0)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "用户不存在";

                        goto EXIT;
                    };

                    //修理厂是否存在
                    sqlc = $"select * from s_usercompany where user_id ='{companyId}'";

                    loginfo.Info(sqlc);
                    ds = mainsql.SqlExcuteWithReturn(sqlc);
                    if (ds.Rows.Count == 0)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "修理厂不存在";

                        goto EXIT;
                    };
                    //是否已经收藏过
                    sqlc = $"select * from S_CompanyCollect where UserId ='{userId}' and CompanyId='{companyId}'";

                    loginfo.Info(sqlc);
                    ds = mainsql.SqlExcuteWithReturn(sqlc);
                    if (ds.Rows.Count != 0)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "店铺已收藏";

                        goto EXIT;
                    };
                    //添加收藏
                    var sqlcmd = $@"INSERT INTO S_CompanyCollect (CollectId,CompanyId,UserId)
                         VALUES ('{collectId}','{companyId}','{userId}')";

                    loginfo.Info($"添加店铺收藏：{sqlcmd}");

                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret > 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "收藏成功";
                        ret.Map_Args["CollectId"] = collectId;
                        ret.Byte_Flag = (sbyte)1;
                    }

                    mainsql.closesql();
                    tsall.Complete();
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion
        #region 取消店铺收藏
        [WebMethod(Description = "取消店铺收藏")]
        public string S_CompanyCollect_D(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            loginfo.Info(nameof(Shop_UpdateCommodityStatus) + ":" + msg);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);

            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    string collectId = comrcv.Map_Args["collectId"];//收藏ID
                    string userId = comrcv.Map_Args["userId"];//用户onlyId
                    //用户是否存在
                    var sqlc = $"select * from yonghualluser where user_onlyid='{userId}'";
                    var ds = mainsql.SqlExcuteWithReturn(sqlc);
                    if (ds.Rows.Count == 0)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "用户不存在";

                        goto EXIT;
                    };

                    //收藏是否存在
                    sqlc = $"select * from S_CompanyCollect where UserId ='{userId}' and CollectId='{collectId}'";

                    loginfo.Info(sqlc);
                    ds = mainsql.SqlExcuteWithReturn(sqlc);
                    if (ds.Rows.Count == 0)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "收藏记录不存在";

                        goto EXIT;
                    };
                    //取消收藏
                    var sqlcmd = $"DELETE FROM S_CompanyCollect where  UserId ='{userId}' and CollectId='{collectId}'";

                    loginfo.Info($"取消店铺收藏：{sqlcmd}");

                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret > 0)
                    {
                        ret.Map_Args["ErrorMsg"] = "取消成功";
                        ret.Byte_Flag = (sbyte)1;
                    }

                    mainsql.closesql();
                    tsall.Complete();
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion
        #region 用户查询收藏店铺列表
        [WebMethod(Description = "用户查询收藏店铺列表")]
        public string S_CompanyCollect_List(string msg)
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            byte[] bytrcv = Convert.FromBase64String(msg);
            var isjson = true;
            ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    string sqlwhere = string.Format(" WHERE 1=1 ");
                    string yonghu_latitude = "";
                    string yonghu_longitude = "";
                    string userId = comrcv.Map_Args["userId"];
                    if (string.IsNullOrEmpty(userId))
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "用户ID为空";
                        goto EXIT;
                    }
                    if (!string.IsNullOrEmpty(comrcv.Map_Args["longitude"]))
                    {
                        yonghu_longitude = comrcv.Map_Args["longitude"];
                        yonghu_latitude = comrcv.Map_Args["latitude"];
                    }
                    string julistr = string.Format("select shop.* from( " +
                       "select * , round(st_distance_sphere(point({0},{1}), point(`user_longitude`,`user_latitude`))) dis " +
                       "from {2}  where user_id in(select CompanyId from S_CompanyCollect s where s.UserId={3} ) shop  ", yonghu_longitude, yonghu_latitude, BIAOUSERCOMPANY, userId);

                    loginfo.Info(string.Format("select t1.*,t2.* from ({0}) t1 left join {1} t2 on t1.user_mentou=t2.file_id  {2} order by dis ;", julistr, BIAOSHOPFILE, sqlwhere.ToString()));
                    var ds = mainsql.SqlExcuteWithReturn(string.Format("select t1.*,t2.* from ({0}) t1 left join {1} t2 on t1.user_mentou=t2.file_id  {2} order by dis ;", julistr, BIAOSHOPFILE, sqlwhere.ToString()));

                    ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();

                    ret.Maplist_MapArgs.Add("Datas", ds.ToModels());
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion

        #region 查询修理厂产品类型(首页)
        [WebMethod(Description = "查询修理厂产品类型(首页)")]
        public string Get_S_Commpditytype_Index()
        {
            ILog loginfo = LogManager.GetLogger("LoggerJieKou");
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            var isjson = true;
            mysqlcli mainsql = new mysqlcli();
            mainsql.openShopServicesql();

            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    string julistr = "select * from s_commpditytype where commpdity_type_status=1 and IsShowIndex=1 order by Sort asc";
                    loginfo.Info(julistr);
                    var ds = mainsql.SqlExcuteWithReturn(julistr);
                    foreach (DataRow dr in ds.Rows)
                    {
                        if (!string.IsNullOrEmpty(dr["Icon"].ToString()))
                        {
                            dr["Icon"] = ConfigurationManager.AppSettings["MinAppStaic"] + dr["Icon"].ToString();
                        }
                    }
                    ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();

                    ret.Maplist_MapArgs.Add("Datas", ds.ToModels());
                    mainsql.closesql();
                    tsall.Complete();
                    ret.Byte_Flag = (sbyte)1;
                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
                loginfo.Info(ex);
            }

        EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        #endregion
    }
}
